[英]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()
and u.save()
both perform the same save()
function. UserDetails.objects.create()
和u.save()
都执行相同的save()
函数。 What is the difference?有什么不同? Is there any extra check or benefit in using
create()
vs save()
?使用
create()
与save()
有什么额外的检查或好处吗?
Similar questions:类似问题:
The Django documentation says it is the same . Django 文档说它是一样的。 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.您也可以在一行上创建一个
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_insert
parameter is documented elsewhere, but all it means is that a new object will always be created.force_insert
参数在别处有文档说明,但这意味着总是会创建一个新对象。 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 anIntegrityError
since primary keys must be unique.但是,如果您的模型包含您设置的手动主键值,并且该值已存在于数据库中,则对
create()
的调用将失败并显示IntegrityError
因为主键必须是唯一的。 Be prepared to handle the exception if you are using manual primary keys.如果您使用手动主键,请准备好处理异常。
Similar question: Django Model() vs Model.objects.create()类似问题: Django Model() vs Model.objects.create()
The difference between Model()
vs Model.objects.create()
are summarized as below. Model()
与Model.objects.create()
之间的区别总结如下。
.save()
perform internally as either INSERT or UPDATE object to db, while .objects.create()
perform only INSERT object to db. .save()
在内部作为对 db 的INSERT或UPDATE对象执行,而.objects.create()
仅对 db 执行INSERT对象。
Model.save()
perform .... Model.save()
执行....
UPDATE → If the object's primary key attribute is set to a value that evaluates to True
UPDATE → 如果对象的主键属性设置为计算结果为
True
的值
INSERT → If the object's primary key attribute is not set or if the UPDATE didn't update anything (eg if primary key is set to a value that doesn't exist in the database). INSERT → 如果对象的主键属性未设置或 UPDATE 未更新任何内容(例如,如果主键设置为数据库中不存在的值)。
If primary key attribute is set to a value then Model.save()
perform UPDATE but Model.objects.create
raise IntegrityError
.如果主键属性设置为一个值,则
Model.save()
执行UPDATE但Model.objects.create
引发IntegrityError
。
eg.例如。
models.py模型.py
class Subject(models.Model): subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id') name = models.CharField(max_length=255) max_marks = models.PositiveIntegerField()
1) Insert/Update to db with Model.save()
1) 使用
Model.save()
插入/更新到数据库
physics = Subject(subject_id=1, name='Physics', max_marks=100) physics.save() math = Subject(subject_id=1, name='Math', max_marks=50) # Case of update math.save()
Output:输出:
Subject.objects.all().values() <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
2) Insert to db with Model.objects.create()
2) 使用
Model.objects.create()
插入数据库
Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100) IntegrityError: UNIQUE constraint failed: m****t.subject_id
Explanation: Above math.save()
is case of update since subject_id
is primary key and subject_id=1
exists django internally perform UPDATE , name Physics to Math and max_marks from 100 to 50 for this, but objects.create() raise IntegrityError
说明:上面的
math.save()
是更新的情况,因为subject_id
是主键并且subject_id=1
存在 django 在内部执行UPDATE ,为此将 Physics 命名为 Math 和 max_marks 从 100 到 50 ,但是objects.create() raise IntegrityError
Model.objects.create()
not equivalent to Model.save()
however same can be achieved with force_insert=True
parameter on save
method ie Model.save(force_insert=True)
. Model.objects.create()
不等同于Model.save()
但是同样可以用force_insert=True
参数在save
方法上实现,即Model.save(force_insert=True)
。Model.save()
return None
where Model.objects.create()
return model instance ie package_name.models.Model
Model.save()
return None
where Model.objects.create()
返回模型实例,即package_name.models.Model
Conclusion: Model.objects.create()
internally do model initialization and perform save
with force_insert=True
.结论:
Model.objects.create()
内部进行模型初始化并使用force_insert=True
执行save
。
source-code block of Model.objects.create() Model.objects.create() 的源代码块
def create(self, **kwargs):
"""
Create 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
The following links can be followed for more details:可以通过以下链接了解更多详细信息:
https://docs.djangoproject.com/en/stable/ref/models/querysets/#create https://docs.djangoproject.com/en/stable/ref/models/querysets/#create
https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440 https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.