创建 Django 模型或更新(如果存在) [英] Create Django model or update if exists
本文介绍了创建 Django 模型或更新(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个模型对象,比如 Person,如果 person 的 id 不存在,或者我会得到那个 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.
创建新人的代码如下:
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
但我不知道在哪里检查和获取现有的person对象.
But I don't know where to check and get the existing person object.
推荐答案
如果您正在寻找如果存在则更新,否则创建"用例,请参考 @Zags 很好的答案
If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer
Django 已经有一个 get_or_create
,https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
Django already has a get_or_create
, https://docs.djangoproject.com/en/dev/ref/models/querysets/#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 one
这篇关于创建 Django 模型或更新(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文