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.
Follow the steps below.
book = Book.objects.get(book_name='Learn Python') book.sale_count += 1 book.save()
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.
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 book.save()
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?
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.