how to add property/attribute/??? to queryset (lik

2019-09-20 15:10发布

I have two querysets:

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'))

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

UPD:

template:

{% 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 %}

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.

标签: django
1条回答
Lonely孤独者°
2楼-- · 2019-09-20 15:56

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]

Then use {{ category.one_year_ago_avg }} in template

查看更多
登录 后发表回答