How to use F() Expression in 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 product.save()
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 product.save()
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 product.save() # price = Decimal('11.00') product.name = 'What the F()' product.save() # 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 product.save() print(product.price) # <CombinedExpression: F(price) + Value(1)> product.refresh_from_db() print(product.price) # Decimal('13.00')
So, You can also use it to annotate data:
from django.db.models import ExpressionWrapper, DecimalField Product.objects.all().annotate( value_in_stock=ExpressionWrapper( 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.
Product.objects.filter(stock__gte=F('ordered'))
I Hope It will help you....