Django计数过滤器和manytomany字段

时间:2014-06-26 22:11:36

标签: django count

我有这个模特。

class Video(models.Model):
    votes = models.ManyToManyField(User, through='moderationVote', related_name='vt')


class moderationVote(models.Model):
   user = models.ForeignKey(User)
   video = models.ForeignKey(Video, related_name='video')
   vote = models.CharField(choices=possible_values, max_length=30)
   date = models.DateTimeField(auto_now_add=True)

现在,在管理员列表中,我想在'list_display'计数中添加另一列,'ok'投票数,'not ok'投票数和'中立'投票数除了使其可以排序通过这个领域。我试图在modeladmin中覆盖'queryset'方法,但我不知道如何进行这种查询。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

编辑:我简化了您的模型关系......

我不确定我是否完全理解您的模型,但这是尝试解决您的问题......

您需要在models.py中执行的操作是为列表显示中的每个列定义property,然后将其包含在admin.py文件中。

您还没有列出possible_values的内容,所以我猜测下面的代码:

class Video(models.Model):

    '''Video model'''

    # I ADDED THIS FIELD
    title = models.CharField(max_length=255)
    # UNLESS I AM MISSING SOMETHING, YOU DON'T EVEN NEED THIS....
    # YOU ALREADY HAVE A ForeignKey RELATION IN ModerationVote....
    # votes = models.ManyToManyField(User, through='moderationVote', related_name='vt')

    @property
    def ok_votes(self):
        return self.moderationvote_set.all().filter(vote='ok').count()

    @property
    def not_ok_votes(self):
        return self.moderationvote_set.all().filter(vote='not_ok').count()

    @property
    def neutral_votes(self):
        return self.moderationvote_set.all().filter(vote='neutral').count()

    class Meta:
        ordering = ['title', ]

class ModerationVote(models.Model):

    '''ModerationVote model'''

    possible_values = ( 
        ('ok', 'ok'),
        ('not_ok', 'not_ok'),
        ('neutral', 'neutral'),
    )   

    user = models.ForeignKey(User)
    video = models.ForeignKey(Video)
    vote = models.CharField(choices=possible_values, max_length=30)
    date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return '%s - %s' % (self.user, self.video)

然后在admin.py中,您可以像其他字段一样调用这些属性:

class VideoAdmin(admin.ModelAdmin):
     # All your other admin goodness...
     list_display = ('votes',
                     'ok_votes',
                     'notok_votes',
                     'neutral_votes',
     )