我有这个模特。
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'方法,但我不知道如何进行这种查询。
有人可以帮助我吗?
答案 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',
)