When to use update_or_create in Django?

The TLDR answer:

If you have used get_or_create you must have had the thought of if there is any Django ORM that could update_or_create. Well, Django has the exact implementation which can either update the DB object if present, else it would create a new object.

class Profile(models.Models):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    gender = models.CharField(max_length=1)
    age = models.IntegerField()

updated_values = {'gender': 'M', age=10}

obj, created = Profile.objects.update_or_create(
    first_name='Argo', last_name='Saha',
    defaults=updated_values
)

Here I am trying to filter the Profile table on first_name and last_name fields. Once the row is matching then update_or_create would update the row and save it back. But if there isn't any possible match then it would create a new DB object.


The Detailed Answer:

Here are the steps which take place under the hood when we run update_or_create query -

  • Fire an update SQL query to the database to see if the entry is present with first_name='Argo and last_name='Saha' and update data with the fields
  • If the data is present in the database then obj would have the updated entry
  • Else a new query would be fired to create a new entry in the database with first_name='Argo and last_name='Saha' and any data which is supplied in defaults field.

update_or_create can also be written in the following way -

updated_values = {'gender': 'M', age=10}

try:
    obj = Profile.objects.get(first_name='Argo', last_name='Saha')
    for key, value in updated_values.iteritems():
        setattr(obj, key, value)
    obj.save()
except Profile.DoesNotExist:
    obj = Profile(first_name='Argo', last_name='Saha', age=10, gender='M')
    obj.save()

which can easily be simplified by

updated_values = {'gender': 'M', age=10}

obj, created = Profile.objects.update_or_create(
    first_name='Argo', last_name='Saha',
    defaults=updated_values
)

update_or_create returns a tuple obj containing the updating a value and created would have a boolean field signifying whether the row is created using this query or it updated.

You can read more about this in the official docs

QuerySet API reference | Django documentation | Django

If you want to read how get_or_create works you can look into the following blog

How to use get_or_create in Django?
The TLDR answerThis is one of those two query one command ORM method. It would make a query tothe database with the given where clause query and if not found then it willcreate a new entry in the table using the default values. It returns a tuple which has the object and a boolean field saying w…