Getting the last member of a group on an intermediary M2M

Posted by rh0dium on Stack Overflow See other posts from Stack Overflow or by rh0dium
Published on 2011-11-29T23:36:24Z Indexed on 2011/11/30 1:51 UTC
Read the original article Hit count: 123

Filed under:
|

If we look at the existing docs, what is the best way to get the last member added? This is similar to this but what I want to do is to be able to do this.

group = Group.objects.get(id=1)
group.get_last_member_added()  #This is by ('-date_added')
<Person: FOO>

I think the best way is through a manager but how do you do this on an intermediary model?

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models