Python django orm 中objects.create() 和object.save() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23926385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:42:20  来源:igfitidea点击:

difference between objects.create() and object.save() in django orm

pythondjangoorm

提问by jacquel

u = UserDetails.objects.create(first_name='jake',last_name='sullivan')
u.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()?

UserDetails.objects.create()并且u.save()两者都执行相同的save()功能。有什么不同?使用create()vs有什么额外的检查或好处save()吗?

Similar questions:
- What's the best way to create a model object in Django?
- Django: Difference between save() and create() from transaction perspective

类似的问题:
-在 Django 中创建模型对象的最佳方法是什么?
- Django:从事务角度看 save() 和 create() 的区别

采纳答案by Maxime Lorant

The Django documentation says it is the same. It is just more convenientto 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.

Django 文档说它是一样的。这仅仅是更方便,使其在同一行。您也可以save()在一行上创建一个,但它会更冗长且可读性更低——很明显,您正在使用该create()方法创建一个新对象。

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")

and:

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

are equivalent.

The force_insertparameter 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 IntegrityErrorsince primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.

create(**kwargs)

一种创建对象并将其全部保存在一个步骤中的便捷方法。因此:

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因为主键必须是唯一的。如果您使用手动主键,请准备好处理异常。