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='Argoandlast_name='Saha'and update data with the fields - If the data is present in the database then
objwould have the updated entry - Else a new query would be fired to create a new entry in the database with
first_name='Argoandlast_name='Saha'and any data which is supplied indefaultsfield.
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
If you want to read how get_or_create works you can look into the following blog
