About Avoiding Race Conditions
Use the F() function to refer to the database field directly instead of the model field attribute in Python when incrementing values to avoid race conditions:
from django.db.models import F
post = Post.objects.get(slug="hello-world")
post.views = F("views") + 1
post.save()
post.refresh_from_db() # Reload with the updated value
This is somewhat analogous to:
Post.objects.filter(
slug="hello-world"
).update(
views=F("views") + 1
)
post = Post.objects.get(slug="hello-world")
Tips and Tricks Programming Databases Django 6.x Django 5.2 Django 4.2 Django ORM
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.