Django F expression for increment

Nov 28, 2016

Django F expressions can be used to manipulate object fields in the database without pulling them out to the application layer. An use case is when a field needs to be incremented. The less then ideal way to do so would be (courtesy: Django docs):

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()

The same code can be rewritten using Django's F expression (courtesy: Django docs):

from django.db.models import F

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

The example code above is a safe because the increment takes place in the DB layer and thus prevents the possibilities of race condition due to multiple agents in the application layer trying to update the same row.

Furhter, the number of queries in the above example can be reduced down to two if the update method is used.

reporter = Reporters.objects.filter(name='Tintin')
reporter.update(stories_filed=F('stories_filed') + 1)