创建Django模型或更新(如果存在)(Create Django model or update if exists)

编程入门 行业动态 更新时间:2024-10-16 20:21:01
创建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 person

But 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 one

If 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

更多推荐

本文发布于:2023-04-27 11:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   Create   Django   exists   update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!