Django 模型管理器 objects.create 文档在哪里?

我总是读到,我应该使用

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

但我刚刚看到有一个管理器函数创建,因为我看到一个开源 django 应用程序使用它。

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

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

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

38527 次浏览

It's in the page "QuerySet API reference", linked from the documentation index.

Basically, these two methods are equivalent. The usage of Model.objects.create could be preferred since it is more suited to the style of Django.

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

equivalent to:

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.

create essentially does the same. below is the source code for 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

it creates an instance and then saves it.