Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

database - use variable in django DB subquery

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:

  1. qs = TimeLog.objects.filter(user_id=1, date__gte='2021-01-01').values()

  2. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...