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')}]
我需要按类别和品牌分组,然后总计每个这些字段的总数。做这个的最好方式是什么?
我改变了一些东西,但作为基础的回答! – leeeandroo 2013-03-08 16:30:16
不错的+1 :) – catherine 2013-03-08 23:52:51