简体   繁体   中英

How to use Django Subquery inside Annotate and Sum

I am trying to calculate total revenue for a day. Each DailyTotal contains a count of items sold (items_sold) and a Price those items were sold that day (items_price) (every items is sold for the same price all day). That part is working, but now I need to convert multiply that value by the exchange rate for that day/country.

rate = ExchangeRate.objects.filter(  
    date=OuterRef('date'), 
    country=OuterRef('country')))  

calc_with_rate = Sum(F('items_sold') * F('items_price') * Subquery(rate.values('rate')), output_field=FloatField(),)  

results = DailyTotal.objects.filter(**query_filters).annotate(
    revenue=calc_with_rate)

but I get:

unsupported operand type(s) for +=: 'int' and 'NoneType

I assume it is because rate.values('rate') is not returning a an int.. but I can't do

rate.values('rate')[0]

or I get:

This queryset contains a reference to an outer query and may only be used in a subquery.

so I am not sure how to complete this query?

It looks like you're trying to += with an int and a NoneType - ie one of those two variables is returning empty, and you're trying to add them - since you're not doing it explicitly with a += operand in the code above, I'm assuming it's happening somewhere in the Sum(). Debug what it does there and you'll likely find the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM