[Fixed]-What's the best way to create a model object in Django?

17👍

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.

4👍

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.

👤Othman

3👍

Create is just a convenience proxy for creating a new object with kwargs. As you can see below, it calls save() for you:

From Django Source:

 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

One thing to notice is the force_insert argument to save. This means that Django will always use an INSERT sql statement here and not an UPDATE. The default is false, so in your second example save() will INSERT or UPDATE.

Leave a comment