简体   繁体   English

如何在Annotate和Sum中使用Django子查询

[英]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). 每个DailyTotal都包含一个已售出商品的数量(items_sold)和当日售出的这些商品的价格(items_price)(所有商品全天以相同的价格出售)。 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')没有返回整数。.但是我做不到

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(). 看起来您正在尝试使用int和NoneType进行+ =-即这两个变量之一返回空值,并且您正在尝试添加它们-因为您没有在其中使用+ =操作数来明确地进行操作上面的代码,我假设它发生在Sum()中。 Debug what it does there and you'll likely find the issue. 调试它在那里所做的事情,您可能会发现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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