views:

20

answers:

2

I have a simple many-to-many relationship based around a through class.

class Person(models.Model):
    friends = models.ManyToManyField('self', through='Friendship')

class Friendship(models.Model):
    me = models.ForeignKey(Person)
    them = models.ForeignKey(Person)
    confirmed = models.BooleanField(default=False)

This should, in short, allow somebody to add somebody else as a friend, but the link doesn't exist until the other person confirms it. Simple enough.

I want to add a is_friend(self, user) method to Person. In that I want to do something like:

is_friend(self, user):
    return self.friends.filter(them=user, confirmed=True).count()

But filter only seems to operate on the distant class (in this case Person). Is there any way I can filter on Friendship instead while still using the ManyRelatedManager?

+1  A: 

I'm a bit rusty, but have you tried return Friendship.objects.filter(me=self, them=user, confirmed=True)?

waffle paradox
I have, and yes, this works... I just expected providing a "through" class to give me some shortcuts or database savings. I have other queries in other places that are a lot more complicated than this that would need a query-able shortcut to stop them turning into monstrous, multiple nested queries.
Oli
A: 

Have you tried:

is_friend(self, user):
    return self.friends.filter(friendship__them=user, friendship__confirmed=True).count()
lazerscience