I have been working on this but I can't seem to get there. I would like to make a query that will do the calculations in the database, store the results in variables I can pull back into Django environment. Objective is:
qs = TimeLog.objects.filter(user_id=1, date__gte='2021-01-01').values()
run a subquery on qs to calculate:
2a) Sum the hours_worked for the year(year_hours)
2b) Sum the wages for the year (year_wages)
2c) Sum the hours_worked for the the current month (month_hours)
2d) Sum the wages for the current month (month_wages)
Here are some of things I have been trying
qs.aggregate(Sum('wages'))
qs.aggregate(year_wages=(F('time_worked') * F('hourly_rate')))
qs.filter(date__lte='2021-01-01').aggregate(Sum('wages'), Sum('time_worked'))
Is there a way to do this in one query using DB expressions like F expression or Q objects or any other way so that it is handled by the DB and pull the variables (year_hours, month_hours, year_wages, month_wages)
back in Django environment. Thanks in advance.
NOTE I'm using PostgreSQL.
question from:
https://stackoverflow.com/questions/65930162/use-variable-in-django-db-subquery 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…