Python Django Model() 与 Model.objects.create()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26672077/
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
Django Model() vs Model.objects.create()
提问by 0leg
What it the difference between running two commands:
运行两个命令有什么区别:
foo = FooModel()
and
和
bar = BarModel.objects.create()
Does the second one immediately create a BarModelin the database, while for FooModel, the save()method has to be called explicitly to add it to the database?
第二个是否立即BarModel在数据库中创建 a ,而 for FooModel,save()必须显式调用该方法才能将其添加到数据库中?
采纳答案by madzohan
https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
To create and save an object in a single step, use the
create()method.
要在单个步骤中创建和保存对象,请使用
create()方法。
回答by Oleg Belousov
UPDATE 15.3.2017:
2017 年 3 月 15 日更新:
I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825
我已经就此打开了一个 Django 问题,它似乎在这里被初步接受:https: //code.djangoproject.com/ticket/27825
My experience is that when using the Constructor(ORM) class by references with Django 1.10.5there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property)
example:
我的经验是,当使用Constructor( ORM) 类通过引用与 Django1.10.5时,数据中可能存在一些不一致(即创建的对象的属性可能获取输入数据的类型,而不是 ORM 对象属性的强制类型)示例:
models
models
class Payment(models.Model):
amount_cash = models.DecimalField()
some_test.py- object.create
some_test.py—— object.create
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor.objects.create(**actual_data)
print(type(_obj.amount_cash)) # Decimal
assert created
objs.append(_obj)
return objs
some_test.py- Constructor()
some_test.py—— Constructor()
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor(**actual_data)
print(type(_obj.amount_cash)) # Float
assert created
objs.append(_obj)
return objs
回答by Thomas Leonard
The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:
这两种语法并不等效,可能会导致意外错误。这是一个显示差异的简单示例。如果你有一个模型:
from django.db import models
class Test(models.Model):
added = models.DateTimeField(auto_now_add=True)
And you create a first object:
然后创建第一个对象:
foo = Test.objects.create(pk=1)
Then you try to create an object with the same primary key:
然后尝试创建一个具有相同主键的对象:
foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")
foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")

