In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.
Let’s say you have a
Product class with a
price field, and you want to increase the price of all products in 20%.
A possible solution would be:
Instead you could use an F() expression to update it in a single query:
You can also do it for a single object:
But take care with this kind of assignment. The F() object persist after saving the model.
So, basically after updating a field like that,
product.price will hold an instance of
django.db.models.expressions.CombinedExpression, instead of the actual result. If you want to access the result
You can also use it to annotate data:
Since price is a
DecimalField and stock is a
IntegerField, we need to wrap the expression inside a
It can be used to filter data as well: