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
좋은 +1 :) – catherine