我有一个模特:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
这是来自django官方文档,在备忘单中。 https://docs.djangoproject.com/en/1.10/topics/db/aggregation/
我要做的是计算以下型号的总票数
我在文档中使用Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes'))
。但这不适合我。
class Question(models.Model):
question_text = models.CharField('Question',max_length=200)
pub_date = models.DateTimeField('date published')
owner = models.ForeignKey(User,default=DEFAULT_USER_ID)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
答案 0 :(得分:0)
您的问题模型没有您的选择模型所做的投票
Question.objects.filter(owner_id=1).annotate(total_votes=Sum('choice__votes'))