问题描述
Author.objects.create(name="Joe")
或
an_author = Author(name="Joe")
an_author.save()
这两者有什么区别?哪一个更好?
What's the difference between these two?Which one is better?
类似问题:
- objects.create() 和 object.save 的区别() 在 Django orm 中
- Django:交易中的 save() 和 create() 之间的区别透视
推荐答案
create()
就像对 save()
方法的封装.
create()
is like a wrapper over save()
method.
创建(**kwargs)
一种创建对象并将其全部保存的便捷方法步骤
A convenience method for creating an object and saving it all in one step
Django 1.8 源代码 用于 create()
函数:
Django 1.8 source code for create()
function:
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) # calls the `save()` method here
return obj
对于 create()
, 一个 force_insert
参数在内部调用 save()
时被传递,它强制save()
方法用于执行 SQL INSERT
而不是执行 UPDATE
.会强制在数据库中插入新行.
For create()
, a force_insert
parameter is passed while calling save()
internally which forces the save()
method to perform an SQL INSERT
and not perform an UPDATE
. It will forcibly insert a new row in the database.
对于save()
,将根据对象的主键执行UPDATE
或INSERT
属性值.
For save()
, either an UPDATE
or INSERT
will be performed depending on the object’s primary key attribute value.
这篇关于在 Django 中创建模型对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!