Author.objects.create(name="Joe")
or
an_author = Author(name="Joe")
an_author.save()
What's the difference between these two? Which one is better?
Similar questions:
- difference between objects.create() and object.save() in django orm
- Django: Difference between save() and create() from transaction perspective
Creating objects To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
def __str__( self ): return "something" This will display the objects as something always in the admin interface. Most of the time we name the display name which one could understand using self object.
create()
is like a wrapper over save()
method.
create(**kwargs)
A convenience method for creating an object and saving it all in one step
Django 1.8 source code for create()
function:
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) # calls the `save()` method here
return obj
For create()
, a force_insert
parameter is passed while calling save()
internally which forces the save()
method to perform an SQL INSERT
and not perform an UPDATE
. It will forcibly insert a new row in the database.
For save()
, either an UPDATE
or INSERT
will be performed depending on the object’s primary key attribute value.
The first one you are using the Manager
method create
. It already implemented for you and it will save automatically.
The second method you are creating an instance of class Author
then you are calling save.
So in conclusion,
Author.objects.create(name="Joe")
create --> save()
the other one first line do create, and second line do save.
in some cases, you will need to call the manager method always. For example, you need to hash the password.
# In here you are saving the un hashed password.
user = User(username="John")
user.password = "112233"
user.save()
# In here you are using the manager method,
# which provide for you hashing before saving the password.
user = User.objects.create_user(username="John", password="112233")
So basically, in your models think about it as setters. If you want to modify the data always while creation then use managers.
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