How to Update Field in Django Model Efficiently??

How to Update Field in Django Model Efficiently??

Let’s say you have the Django model defined as

class Book(models.Model):
    book_name = models.CharField(max_length=120)
    writen_by = models.ForeignKey(Author, on_delete=models.CASCADE, null=True)
    sale_count = models.PositiveIntegerField(blank=True, null=True)

There is a field “sale_count” that maintains the number of sales for the book.

Sometimes we need to perform a simple arithmetic operation on a field value, such as incrementing or decrementing the existing value. 

Here, in this example, we want to increase the sale of a book named “Learn Python” by one.

Here are a couple of ways to achieve the desired job.

Method 1: Obvious Way

Follow the steps below.

  • Get the object of the model “Book” which has book name as “Learn Python”
  • Update the field “sale_count” for then model “Book”.
  • Save the object.
book = Book.objects.get(book_name='Learn Python')
book.sale_count += 1

If the current value of the “sale_count” is 25, after executing the above lines of code, the updated value of the “sale_count” becomes 26 which will be saved in the database.

Here we are just updating the single field attribute, you update multiple fields as well.

Method 2: Using F Expression

You can also use the F expression to do the same job.

from django.db.models import F

book = Book.objects.get(book_name='Learn Python')
book.sale_count = F('sale_count') + 1

Note: You have to import the F expression before using it.

Basically, these are the two methods you can use to update field in Django model.

Now the question is- which one you should use?

Which is more efficient to update the field in the Django model?

Using F expression is slightly faster by expressing the update relative to the original field value, rather than as an explicit assignment of a new value.

If you have any doubts, let’s discuss them in the comment section below.


Leave a Reply

Your email address will not be published. Required fields are marked *