Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create a model object in Django?

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

like image 549
Brian Avatar asked Jul 25 '15 07:07

Brian


People also ask

How do you create a model object in Python?

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

What is def __ str __( self in Django model?

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.


2 Answers

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.

like image 171
Rahul Gupta Avatar answered Sep 19 '22 15:09

Rahul Gupta


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.

like image 26
Othman Avatar answered Sep 21 '22 15:09

Othman