运行两个命令有什么不同:

foo = FooModel()

and

bar = BarModel.objects.create()

第二个方法是否立即在数据库中创建一个BarModel,而对于FooModel,必须显式调用save()方法将其添加到数据库中?


https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects

要在一个步骤中创建和保存对象,请使用create()方法。


更新15.3.2017:

我已经开了一个django的问题,这似乎是初步接受这里: https://code.djangoproject.com/ticket/27825

我的经验是,当Django 1.10.5通过引用使用构造函数(ORM)类时,数据中可能会有一些不一致(即创建对象的属性可能获得输入数据的类型,而不是ORM对象属性的强制类型) 例子:

模型

class Payment(models.Model):
     amount_cash = models.DecimalField()

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 -构造函数()

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

这两种语法不相等,可能会导致意外错误。 下面是一个简单的例子来说明它们之间的区别。 如果你有一个模型:

from django.db import models

class Test(models.Model):

    added = models.DateTimeField(auto_now_add=True)

然后创建第一个对象:

foo = Test.objects.create(pk=1)

然后尝试创建一个具有相同主键的对象:

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

Model()和Model.objects.create()之间的区别如下:


插入与更新 Model.save()对DB中的对象执行INSERT或UPDATE操作,而Model.objects.create()只执行INSERT操作。 Model.save () UPDATE如果对象的主键属性被设置为值为True 如果对象的主键属性没有设置,或者UPDATE没有更新任何东西(例如,如果主键设置为数据库中不存在的值)。


Existing primary key If primary key attribute is set to a value and such primary key already exists, then Model.save() performs UPDATE, but Model.objects.create() raises IntegrityError. Consider the following models.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() Insert/Update to db with 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() Result: Subject.objects.all().values() <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]> Insert to db with Model.objects.create() Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100) IntegrityError: UNIQUE constraint failed: m****t.subject_id Explanation: In the example, math.save() does an UPDATE (changes name from Physics to Math, and max_marks from 100 to 50), because subject_id is a primary key and subject_id=1 already exists in the DB. But Subject.objects.create() raises IntegrityError, because, again the primary key subject_id with the value 1 already exists.


强行插入 Model.save()可以通过使用force_insert=True参数使其表现为Model.objects.create(): Model.save(force_insert=True)。


返回值 model .objects.create()返回模型实例,即package_name.models.Model


结论:model .objects.create()执行模型初始化并使用force_insert=True执行save()。

摘自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

更多详情请点击以下链接:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#create https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440


create()创建一个模型实例并保存它。Model()只创建内存中的模型实例。在调用实例的save()方法保存它之前,它不会保存到数据库。这也是验证发生的时候。