How To Execute Arithmetic Operations Between Model Fields In Django
Solution 1:
F() expressions can be used to execute arithmetic operations (+, -, * etc.) among model fields, in order to define an algebraic lookup/connection between them.
An
F()object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
let's tackle the issues then:
The product of two fields:
result = MyModel.objects.all().annotate(prod=F('number_1') * F('number_2'))Now every item in
resulthas an extra column named 'prod' which contains the product ofnumber_1andnumber_2of each item respectively.Filter by day difference:
from datetime import timedelta result = MyModel.objects.all().annotate( delta=F('date_2') - F('date_1') ).filter(delta__gte=timedelta(days=10))Now the items in
resultare those fromMyModelwhosedate_2is 10 or more days older thandate_1. These items have a new column nameddeltawith that difference.A different case:
We can even use
F()expressions to make arithmetic operations on annotated columns as follows:result= MyModel.objects.all() .annotate(sum_1=Sum('number_1')) .annotate(sum_2=Sum('number_2')) .annotate(sum_diff=F('sum_2') - F('sum_1'))
Post a Comment for "How To Execute Arithmetic Operations Between Model Fields In Django"