Django计算模型层中的相关对象

时间:2011-05-11 15:06:27

标签: django average vote

可以做这样的工作:

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

2 个答案:

答案 0 :(得分: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())

如果有效,请告诉我。我还没有测试过。

答案 1 :(得分: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

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