0

我使用 Django 1.4 和 Py 2.7,我需要合并一些 QuerySetValues 并对字段“total”求和。

我的模型是:

class CategoryAnswers(models.Model):
    category = models.ForeignKey(Category, verbose_name="Category")
    answer = models.DecimalField("Resposta", default=0, decimal_places=2, max_digits=4)
    brand = models.ForeignKey(Brand, verbose_name="Brand")

    class Meta:
        db_table = 'category_answers'
        verbose_name = "CategoryAnswers"
        verbose_name_plural = "CategoryAnswers"


    def __unicode__(self):
        return self.category.name 

class Answers(models.Model):
    category_answers = models.ManyToManyField(CategoryAnswers, verbose_name="CategoryAnswers")    
    user = models.ForeignKey(User, verbose_name="User")
    campaign = models.ForeignKey(Campaign,verbose_name="Campaign")

    class Meta:
        db_table = 'answers'
        verbose_name = "Answers"
        verbose_name_plural = "Answers"


    def __unicode__(self):
        return 'Answers'

当我搜索使用以下代码对字段进行分组所需的所有记录时:

for answer in answers:
        print answer.category_answers.all().values('brand','category').annotate(total=Sum('answer'))

返回这个:

[{'category': 7L, 'brand': 8L, 'total': Decimal('5.00')}, {'category': 3L, 'brand': 5L, 'total': Decimal('5.00')}, {'category': 4L, 'brand': 8L, 'total': Decimal('4.00')}, {'category': 2L, 'brand': 1L, 'total': Decimal('4.00')}, {'category': 4L, 'brand': 5L, 'total': Decimal('3.00')}]

[{'category': 7L, 'brand': 8L, 'total': Decimal('5.00')}, {'category': 3L, 'brand': 5L, 'total': Decimal('8.00')}, {'category': 4L, 'brand': 8L, 'total': Decimal('7.00')}, {'category': 2L, 'brand': 1L, 'total': Decimal('5.00')}, {'category': 4L, 'brand': 5L, 'total': Decimal('4.00')}]

[{'category': 7L, 'brand': 8L, 'total': Decimal('5.00')}, {'category': 3L, 'brand': 5L, 'total': Decimal('6.00')}, {'category': 4L, 'brand': 8L, 'total': Decimal('6.00')}, {'category': 2L, 'brand': 1L, 'total': Decimal('7.00')}, {'category': 4L, 'brand': 5L, 'total': Decimal('7.00')}]

我需要按类别和品牌分组,并对每个字段求和。做这个的最好方式是什么?

4

2 回答 2

2
categories=CategoryAnswers.objects.values_list('category', 'brand').distinct()

for cat in categories:
    print CategoryAnswers.objects.filter(
        category=cat.category, brand=cat.brand).annotate(total=Sum('answer'))
于 2013-03-08T16:15:41.997 回答
1
categories=CategoryAnswers.objects.values('category', 'brand').distinct()
for cat in categories:
    print CategoryAnswers.objects.filter(category=cat["category"], brand=cat["brand"]).values('category', 'brand').annotate(total=Sum('answer'))
于 2013-03-08T16:32:24.357 回答