0

I have this models.

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)

Now, in the admin list i'd like to add another column to 'list_display' counting, the number of 'ok' votes, the 'not ok' votes, and the 'neutral' votes, besides to make it sortable by this field. I have tried to overrite the 'queryset' method in the modeladmin, but I don't know how to make this kind of query.

Can anyone please help me?

Miki Torandell
  • 163
  • 1
  • 11

1 Answers1

1

EDIT: I have simplified your model relationships.....

I am not sure I fully understand your models, but here is an attempt to solve your problem...

What you need to do in your models.py is define a property for each column you want in the list display, then just include it in your admin.py file.

You haven't listed what your possible_values are, so I am guessing in the code below:

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)

Then in your admin.py you just call these properties like any other field:

class VideoAdmin(admin.ModelAdmin):
     # All your other admin goodness...
     list_display = ('votes',
                     'ok_votes',
                     'notok_votes',
                     'neutral_votes',
     )
tatlar
  • 3,080
  • 2
  • 29
  • 40
  • Thanks @tatlar, but the problem with 'propertyes' is that is not sortable by clicking in the table 'th' in the list_display view. Any idea? – Miki Torandell Jun 26 '14 at 23:22
  • [Check this related question and answer out](http://stackoverflow.com/questions/2168475/) – tatlar Jun 27 '14 at 16:51