简体   繁体   English

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

[英]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 an IntegrityError 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()之间的区别总结如下。


  1. .save() perform internally as either INSERT or UPDATE object to db, while .objects.create() perform only INSERT object to db. .save()在内部作为对 db 的INSERTUPDATE对象执行,而.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 未更新任何内容(例如,如果主键设置为数据库中不存在的值)。


  1. If primary key attribute is set to a value then Model.save() perform UPDATE but Model.objects.create raise IntegrityError .如果主键属性设置为一个值,则Model.save()执行UPDATEModel.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


  1. 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)

  1. 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:可以通过以下链接了解更多详细信息:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. 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

Note: Above answer is from question .注意:以上答案来自问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "Django Postgres objects.create ValidationError" - Django Postgres objects.create ValidationError Django模型管理器objects.create文档在哪里? - Django model manager objects.create where is the documentation? 聚合/优化object.save()? - Aggregating/optimizing object.save()? orm [&#39;model&#39;]。objects.create(attr = some_value)导致IntegrityError - orm['model'].objects.create(attr=some_value) causes IntegrityError Python-django typeerror: expected string or bytes-like object error — object.save() - Python-django typeerror: expected string or bytes-like object error — object.save() 在第二个object.create之后Django回滚不起作用 - Django rollback not working after second objects.create fails to create a record 如何验证 objects.create() 方法的选择? - How to validate CHOICES for objects.create() method? ManyToMany字段作为.objects.create()函数的参数 - ManyToMany field as an argument to .objects.create() function Django get_user_model().objects.create() 密码没有得到散列 - Django get_user_model().objects.create() password is not getting hashed 在Django测试中,为什么我需要使用 <Model> .objects.get()而不是返回的内容 <Model> .objects.create()? - In Django tests, why do I need to use <Model>.objects.get() instead of what was returned by <Model>.objects.create()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM