I always read that I should use
model = Model(a=5, b=6)
model.save()
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)
print model.pk
1
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: https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects
Since Django only looks for models under the Python path <app>. models , you must declare a relative import in the main models.py file -- for each of the models inside sub-folders -- to make them visible to the app.
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
A model in Django is supposed to correlate to a table in the database, so that each field in the model will actually be a field in the table for that model. To achieve what you're trying to do, you need to create a second model, which will be the object you want to store.
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
equivalent to:
p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)
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.
It's in the page "QuerySet API reference", linked from the documentation index.
create essentially does the same. below is the source code for create.
def create(self, **kwargs):
"""
Creates 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
it creates an instance and then saves it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With