Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between objects.create() and object.save() in django orm

Tags:

python

orm

django

u = UserDetails.objects.create(first_name='jake',last_name='sullivan') u.save() 

UserDetails.objects.create() and u.save() both perform the same save() function. What is the difference? Is there any extra check or benefit in using create() vs save()?

Similar questions:

  • What's the best way to create a model object in Django?
  • Django: Difference between save() and create() from transaction perspective
  • Django Model() vs Model.objects.create()
like image 433
jacquel Avatar asked May 29 '14 05:05

jacquel


People also ask

Does Django objects create save?

Creating objectsTo 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.

What is Django ORM object?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

What is create method in Django?

To answer the question literally, the create method in a model's manager is a standard way to create new objects in Django. To override, do something like from django.db import models class MyModelManager(models.Manager): def create(self, **obj_data): # Do some extra stuff here on the submitted data before saving... #

How use Django save method?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.


2 Answers

The Django documentation says it is the same. It is just more convenient to make it on one line. You could make a save() on one line too, but it would be more verbose and less readable -- it is clear you are creating a new object with the create() method.

create(**kwargs)

A convenience method for creating an object and saving it all in one step. Thus:

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

and:

p = Person(first_name="Bruce", last_name="Springsteen") p.save(force_insert=True) 

are equivalent.

The force_insert parameter is documented elsewhere, but all it means is 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.

like image 131
Maxime Lorant Avatar answered Oct 10 '22 08:10

Maxime Lorant


Similar question: Django Model() vs Model.objects.create()

The difference between Model() vs Model.objects.create() are summarized as below.


  1. .save() perform internally as either INSERT or UPDATE object to db, while .objects.create() perform only INSERT object to db.

    Model.save() perform ....

    UPDATE → If the object’s primary key attribute is set to a value that evaluates to True

    INSERT → If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).


  1. If primary key attribute is set to a value then Model.save() perform UPDATE but Model.objects.create raise IntegrityError.

    eg.

    models.py

    class Subject(models.Model):    subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')    name = models.CharField(max_length=255)    max_marks = models.PositiveIntegerField() 

    1) Insert/Update to db with Model.save()

    physics = Subject(subject_id=1, name='Physics', max_marks=100) physics.save() math = Subject(subject_id=1, name='Math', max_marks=50)  # Case of update math.save() 

    Output:

    Subject.objects.all().values() <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]> 

    2) Insert to db with Model.objects.create()

    Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100) IntegrityError: UNIQUE constraint failed: m****t.subject_id 

    Explanation: Above math.save() is case of update since subject_id is primary key and subject_id=1 exists django internally perform UPDATE, name Physics to Math and max_marks from 100 to 50 for this, but objects.create() raise IntegrityError


  1. Model.objects.create() not equivalent to Model.save() however same can be achieved with force_insert=True parameter on save method i.e Model.save(force_insert=True).

  1. Model.save() return None where Model.objects.create() return model instance i.e. package_name.models.Model

Conclusion: Model.objects.create() internally do model initialization and perform save with force_insert=True.

source-code block of Model.objects.create()

def create(self, **kwargs):     """     Create 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 

The following links can be followed for more details:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440

Note: Above answer is from question.

like image 25
Furkan Siddiqui Avatar answered Oct 10 '22 07:10

Furkan Siddiqui