Django model manager objects.create where is the documentation?


I always read that I should use

model = Model(a=5, b=6)

But I just saw there is a manager function create, because I saw an opensource django app using it.

model = Model.objects.create(a=5, b=6)

So is it suggested to use it? Or is it still preferred to use the .save method. I'm guessing that objects.create will try to create it no matter what, whereas save may save an existing object if the pk is specified.

These are the docs that I found:

3/30/2012 9:51:02 AM

Accepted Answer

It's in the page "QuerySet API reference", linked from the documentation index.

1/17/2018 7:08:17 PM

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

equivalent to:

p = Person(first_name="Bruce", last_name="Springsteen")

The force_insert means that a new object will always be created.
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. Be prepared to handle the exception if you are using manual primary keys.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow