问题
I'm calculating the sold items cost in django views and in django signals, and I want to calculate sold items cost on the fly. Price and quantity fields are integers. How can I convert one of them to the float and make sum query with some calculations like these sql queries below?
SELECT sum((t.price::FLOAT * t.quantity) / 1000) as cost FROM public."sold" t; SELECT t.id, t.price, t.quantity, sum((price::FLOAT * quantity) / 1000) as cost FROM public."sold" t GROUP BY t.id;
EDIT: Of course expected results are querysets of django
I expected the output of first query
cost ----------------- 5732594.000000002
and I expected the output of second query
id price quantity cost ------------------------------ 846 1100 5000 5500 790 1500 1000 1500 828 2600 1000 2600 938 1000 5000 5000 753 1500 2000 3000 652 5000 1520 7600
EDIT 2: I solved this issue via raw()
method like
MyModel.objects.raw( 'SELECT sum((t.price::FLOAT * t.quantity) / 1000) as cost ' 'FROM public."sold" t' )instead of pythonic way
回答1:
You'll need to have a look into a couple of things to do that. The first one will be aggregation and annotation. Also, you'll need to look into Cast and F functions. Please have a look at the links below:
https://docs.djangoproject.com/en/2.2/topics/db/aggregation/
https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#cast
https://docs.djangoproject.com/en/2.2/ref/models/expressions/
DISCLAIMER: This is an example and might not work
Your queryset will look something like this:
from django.db.models import FloatField, Sum
from django.db.models.functions import Cast
qs = MyModel.objects.annotate(cost=Sum(F(Cast('price', FloatField())) * F('quantity') / 1000))
来源:https://stackoverflow.com/questions/56196815/how-to-make-sum-query-with-type-casting-and-calculation-in-django-views