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

查看:98
本文介绍了创建Django模型或更新(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个模型对象,如Person,如果人的id不存在,或者我会得到该对象。

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

但我不知道在哪里检查并获取现有的对象。

But I don't know where to check and get the existing person object.

推荐答案

如果您正在寻找update if exists else create用例,请参考 @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 / 1.9 / REF /模型s / querysets /#获取或创建

Django already has a get_or_create, https://docs.djangoproject.com/en/1.9/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆