django 查询集的总和
我需要对数据集的 django 查询集进行聚合。
我有一个看起来像这样的模型:
class Model1(models.Model):
... some fields here ...
class Model2(models.Model):
model1 = models.ForeignKey(Model1)
number = models.IntegerField()
active = models.BooleanField()
category = models.CharField(choices=...)
它们工作正常,以防我在演示代码中遗漏了拼写错误。我现在想要显示 model1 以及按类别分组的相关 model2。我使用 regroup 模板标签执行此操作(请注意,我有一个名为 model2s 的类方法,它返回与 model2_set.filter(active=True) 相同的所有内容):
{% regroup m1.model2s by category as m2_list %}
然后我通过 regroup 正常显示它们。这东西也很好用。现在,我需要在每个类别组的顶部添加总摘要以及该组的数字总和。因此,如果我有 2 个同一类别的 model2 引用 1 个 Model1,其中一个的 number=1,另一个的 number=2,那么我需要显示 3。
实际上,会有很多 Model2,因此这可以是昂贵的查询。
我查看了文档并查看了聚合和注释,但似乎都不允许我根据类别进行求和。我不想对每个类别都这样做:
m2sum = m1.model2s.filter(category='something').aggregate(Sum('number'))['number__sum']
是否有一种更干净的方法来执行此操作,希望它可以很好地与重组配合使用?
I need to do an aggregation on a django queryset for sets of data.
I have a model that looks something like this:
class Model1(models.Model):
... some fields here ...
class Model2(models.Model):
model1 = models.ForeignKey(Model1)
number = models.IntegerField()
active = models.BooleanField()
category = models.CharField(choices=...)
They work fine, in case there is a typo I missed in that demo code. I now want to display model1s with their related model2s grouped by category. I am doing this using the regroup template tag (note I have a class method called model2s that returns all the same as model2_set.filter(active=True) ):
{% regroup m1.model2s by category as m2_list %}
Then I display them as normal with regroup. This stuff also works fine. Now I need to add a total summary to the top of each category group with the sum of number for that group. So if I had 2 model2s of the same category referencing 1 Model1 and one of those had number=1 and the other had number = 2, then I need to display 3.
In reality there will be a lot of Model2s so this can be an expensive query.
I've looked at the docs and see aggregate and annotate, but neither seems to let me do the sum based on the category. I would like to not have to do this for each category:
m2sum = m1.model2s.filter(category='something').aggregate(Sum('number'))['number__sum']
Is there a cleaner way to do this, hopefully one the works nicely with regroup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很确定您可以使用注释 QuerySet 方法来做到这一点。如果我能找到一个好的例子,我会发布更新。
更新:我认为是这样的......如果我正确理解你的问题。除非您使用计数而不是平均值。
I'm pretty sure you can do this with the annotate QuerySet method. I'll post an update if I can find a good example.
Update: I think something like this.... if I understand your question correctly. Except you would use Count instead of Avg.