How to calculate in django model fields?

(Nehat Khan) #1

I am creating an app that stores the credit details of person. Here is my model design

class credit (models.Model):
customer_name = models.CharField(max_length = 100)
product_name = models.CharField(max_length= 100)
product_quantity = models.IntegerField(defualt=1)
price = models.IntegerField(default = 0)

How I can calculate the price based of quantity automatically, supposed I select 2 quantity of any product and the price automatically gave me the calculation of 2. How can I achieve that. And sorry for my english


(Vitor Freitas) #2

It depends on where the unit price is stored. If the price on the model refer to the unit price, you can annotate a queryset like his:

from django.db.models import F

Credit.objects.annotate(total_price=F('price') * F('product_quantity'))

So in an example where you have product_quantity=4 and price=100, this queryset would give you one additional column created on-the-fly named total_price:

Field Value
product_quantity 4
price 100
total_price 400

Now about the F() expression, it is used to make self references on a database level (referencing some column from the same row).

I have a blog post where I explain about it: