开发者

django sum for a queryset

开发者 https://www.devze.com 2023-03-01 02:34 出处:网络
I need to do an aggregation on a django queryset for sets of data. I have a model that looks something like this:

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 reg开发者_StackOverflow中文版roup?


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.

Author.objects.values('name').annotate(average_rating=Avg('book__rating')) http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values

0

精彩评论

暂无评论...
验证码 换一张
取 消