Django model manager objects.create文档在哪里?

2024-06-16 18:02:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我总是读到我应该用

model = Model(a=5, b=6)
model.save()

但我刚刚看到一个manager函数create,因为我看到一个opensource django应用程序正在使用它。

model = Model.objects.create(a=5, b=6)
print model.pk
1

所以建议使用它吗?还是仍然首选使用.save方法。我猜objects.create无论如何都会尝试创建它,而如果指定了pk,save可能会保存现有的对象。

这些是我找到的文件:https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects


Tags: 对象django方法函数应用程序modelobjectssave
3条回答

create基本上也是这样。下面是create的源代码。

def create(self, **kwargs):
    """
    Creates a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

它创建一个实例,然后保存它。

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

相当于:

p = Person(first_name="Bruce", last_name="Springsteen") 
p.save(force_insert=True)

The force_insert means that a new object will always be created.
Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the database, a call to create() will fail with an IntegrityError since primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.

它在页面"QuerySet API reference"中,从文档索引链接而来。

相关问题 更多 >