django orm中的objects.create()和object.save()之间的区别 [英] difference between objects.create() and object.save() in django orm
问题描述
u = UserDetails.objects.create(first_name='jake',last_name='sullivan')
u.save()
UserDetails.objects.create()
和 u.save ()
都执行相同的 save()
函数。有什么不同?有没有使用 create()
vs save()
?
UserDetails.objects.create()
and u.save()
both perform the same save()
function. What is the difference? Is there any extra check or benefit in using create()
vs save()
?
类似的问题:
- 在Django中创建模型对象的最佳方法是什么?
- Django:从事务角度看save()和create()之间的区别
推荐答案
Django文档说它是一样的。只需更方便即可使其成为一行。您也可以在一行中创建一个 save()
,但它会更加冗长且不太可读 - 很明显,您正在使用 create()
方法。
The Django documentation says it is the same. It is just more convenient to make it on one line. You could make a save()
on one line too, but it would be more verbose and less readable -- it is clear you are creating a new object with the create()
method.
create(** kwargs) / code>
创建对象并将其全部保存在一个
步骤中的便利方法。因此:
create(**kwargs)
A convenience method for creating an object and saving it all in one step. Thus:
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
和:
p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)
是等价的。
force_insert
参数在其他地方记录,
是始终创建一个新的对象。通常你不需要
担心这一点。但是,如果您的模型包含您设置的手动主
键值,并且
数据库中已存在该值,则调用 create()
将失败,一个 IntegrityError
,因为
主键必须是唯一的。如果
正在使用手动主键,则准备处理异常。
The force_insert
parameter is documented elsewhere, but all it means
is 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.
这篇关于django orm中的objects.create()和object.save()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!