1

可以做这样的事情:

class Book(models.Model):
    voters = models.ManyToManyField(User, blank=True)
    vote = models.IntegerField() # summary of all votes
    def average_vote(self):
        return int(vote/self.annotate(Count('voters')))
4

2 回答 2

0

也许是这样的?

class Book(models.Model):
    voters = models.ManyToManyField(User, blank=True)
    vote = models.IntegerField() # summary of all votes

    def average_vote(self):
        return int(self.vote/self.voters.all().count())

让我知道这是否有效。我没有测试过。

于 2011-05-11T15:15:08.747 回答
0

只需覆盖默认管理器以使其始终返回带注释的查询集:

class BookUserManager(models.Manager):
    def get_query_set(self, *args, **kwargs):
        return super(BookUserManager, self).get_query_set(*args, **kwargs).annotate(average_vote=models.Avg('books__vote'))

class BookUser(User):
    objects = BookUserManager()

    class Meta:
        proxy = True

class Book(models.Model):
    # Next line has been changed to use proxy model. This *will* affect the m2m table name.
    voters = models.ManyToManyField(BookUser, blank=True, related_name='books')
    vote = models.IntegerField() # summary of all votes

    objects = BookManager()

然后,您可以像用户模型上的任何其他属性一样获取该值:

user = BookUser.objects.get(username='joe')
print user.average_vote

更新:对不起......全都错了。这就是我过快阅读问题所得到的。您实际上需要注释Usernot Book,但由于User来自django.contrib.auth(我假设)这是不可能的,或者至少它需要更多步骤。上面的代码已经更新。

于 2011-05-11T15:29:07.347 回答