Django, sum of fields in intermediary model with given queryset

℡╲_俬逩灬. 提交于 2019-12-11 08:32:30

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/7070917/django-sum-of-fields-in-intermediary-model-with-given-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!