Django,中间模型中与给定查询集合的字段数 [英] Django, sum of fields in intermediary model with given queryset

查看:111
本文介绍了Django,中间模型中与给定查询集合的字段数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,其中一个与这样的其他表格有很多很多关系。

  class a (models.Model):
#fields
class b(models.Model):
from_a = models.ForeignKey(a)
to_a = models.ForeignKey(a)
count = models.PositiveIntegerField()

现在,我想知道什么是最好的方法计算b的计数总和,其中from_a是某事物。这个似乎是微不足道的,但我无法确定。

解决方案

  from django .db.models import Sum 
b.objects.filter(from_a__whatever ='something')。aggregate(Sum('count'))


I have 2 models, one of them has many to many relation with itself through other table like this.

class a(models.Model):
    # fields
class b(models.Model):
    from_a = models.ForeignKey(a)
    to_a = models.ForeignKey(a)
    count = models.PositiveIntegerField()

Now, what I wonder is, what is the best way of calculating sum of counts in b's where from_a is "something". This one seems trivial, but I can't figure it out.

解决方案

from django.db.models import Sum
b.objects.filter(from_a__whatever='something').aggregate(Sum('count'))

这篇关于Django,中间模型中与给定查询集合的字段数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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