如何添加属性/属性/ ???到查询(如注释) [英] how to add property/attribute/??? to queryset (like annotation)

查看:85
本文介绍了如何添加属性/属性/ ???到查询(如注释)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个查询器:

category_list_avg =Category.objects.filter(operation__date__gte = year_ago).annotate(podsuma = Sum('operation__value'))
category_list = Category.objects.annotate(suma = Sum('operation__value'))

有没有办法使用一个查询(在我的模板中有一个for循环)?

Is there a way to do this with one queryset (there is a for loop in my template)?

UPD

模板:

{% for category in category_list %}
<tr>
  <td><a href="{{ category.id }}/">{{ category.name }}</a></td>
  <td style="text-align:right{% if category.suma|default:0 < 0 %};color:red{% endif %}">
    {{ category.suma|default:0|currency }}</td>
  {% for monthsum in category.get_month_sum_series %}
  <td style="text-align:right{% if monthsum.1 < 0 %};color:red{% endif %}">{{ monthsum.1|currency }}</td>
  {% endfor %}
  <td style="text-align:right">???</td>
</tr>
{% endfor %}

代替???将是平均值(现在我使用子部分的总和 - 因为它更容易调试 - 如果我看到podsuma小于suma - 我会知道它的工作。

in place of ??? would be the average value (now I use sum of subpart - because its easier to debug - if I see that podsuma is less than suma - I would know that it works.

推荐答案

您需要执行另一个查询以获取平均值,并将其附加到视图中或模型中的 category_list

You need to do another query to get average values and attach them to category_list, either in view or in model:

# in view
category_list = Category.objects.annotate(suma = Sum('operation__value'))
one_year_ago_avg = dict(Category.objects.filter(operation__date__gte = year_ago).annotate(avg = Avg('operation__value')).values_list('pk', 'avg'))
for cat in category_list:
    cat.one_year_ago_avg = one_year_ago_avg.get(cat.pk)


# or in model
class Category(models.Model):
    def one_year_ago_avg(self):
        year_ago = ...
        return self.operation_set.filter(date__gte=year_ago).aggregate(Avg('value')).values()[0]

然后使用 {{ca tegory.one_year_ago_avg}} 在模板中

这篇关于如何添加属性/属性/ ???到查询(如注释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆