2013-03-08 44 views
0

我與Django 1.4和Py 2.7一起工作,我需要合併一些QuerySetValues並總結字段「total」。合併Django中的QuerySetValues對象

我的模式是:

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')}] 

我需要按類別和品牌分組,然後總計每個這些字段的總數。做這個的最好方式是什麼?

回答

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')) 
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')) 
+0

我改變了一些東西,但作爲基礎的回答! – leeeandroo 2013-03-08 16:30:16

+0

不錯的+1 :) – catherine 2013-03-08 23:52:51