How to use F() Expression in Django?

Published On: 25/11/2022 | Category: Django

Hi Dev,

Now, let's see post of how to use f() expression in django. I explained simply step by step how to use f expression in python django. you will learn django f() expression example tutorial. you can see django f() expression. Let's get started with f expression in django.

F() expressions are used in the Django QuerySet API to refer to model field values directly in the database. Assume you have a Product class with a price field and wish to raise the price of all products by 20%.

Here i explained simply step by step example of how to use f() expression in django.

One possible solution is:

products = Product.objects.all()
for product in products:
    product.price *= 1.2

You could instead use an F() expression to update it in a single query:

from django.db.models import F

Product.objects.update(price=F('price') * 1.2)

It's also possible to do it for a single object:

product = Product.objects.get(pk=5009)
product.price = F('price') * 1.2

But be cautious with this type of assignment. After saving the model, the F() object remains.

product.price                   # price = Decimal('10.00')
product.price = F('price') + 1                  # price = Decimal('11.00') = 'What the F()'                  # price = Decimal('12.00')

So, after updating such a field, product.price will hold an instance of django.db.models.expressions. Instead of the actual result, use CombinedExpression. If you want to see the result right away:

product.price = F('price') + 1
print(product.price)            # <CombinedExpression: F(price) + Value(1)>
print(product.price)            # Decimal('13.00')

So, You can also use it to annotate data:

from django.db.models import ExpressionWrapper, DecimalField

        F('price') * F('stock'), output_field=DecimalField()

Because price is a DecimalField and stock is an IntegerField, the expression must be wrapped in an ExpressionWrapper object.


I Hope It will help you....