Django Model() vs Model.objects.create()

前端 未结 4 1217
执笔经年
执笔经年 2020-12-04 06:06

What it the difference between running two commands:

foo = FooModel()

and

bar = BarModel.objects.create()

4条回答
  •  执笔经年
    2020-12-04 06:20

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

提交回复
热议问题