创建Django模型或更新(如果存在)(Create Django model or update if exists)
我想创建一个模型对象,如Person,如果人的id不存在,或者我会得到那个人的对象。
创建新人的代码如下:
class Person(models.Model): identifier = models.CharField(max_length = 10) name = models.CharField(max_length = 20) objects = PersonManager() class PersonManager(models.Manager): def create_person(self, identifier): person = self.create(identifier = identifier) return person但我不知道在哪里检查并获得现有的人物。
I want to create a model object, like Person, if person's id doesn't not exist, or I will get that person object.
The code to create a new person as following:
class Person(models.Model): identifier = models.CharField(max_length = 10) name = models.CharField(max_length = 20) objects = PersonManager() class PersonManager(models.Manager): def create_person(self, identifier): person = self.create(identifier = identifier) return personBut I don't know where to check and get the existing person object.
最满意答案
如果您正在寻找“更新如果存在其他创建”用例,请参阅@Zags优秀的答案
Django已经有一个get_or_create , https : get_or_create
对你来说可能是:
id = 'some identifier' person, created = Person.objects.get_or_create(identifier=id) if created: # means you have created a new person else: # person just refers to the existing oneIf you're looking for "update if exists else create" use case, please refer to @Zags excellent answer
Django already has a get_or_create, https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
For you it could be :
id = 'some identifier' person, created = Person.objects.get_or_create(identifier=id) if created: # means you have created a new person else: # person just refers to the existing one更多推荐
发布评论