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(th开发者_JS百科em=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
?
I'm a bit rusty, but have you tried return Friendship.objects.filter(me=self, them=user, confirmed=True)
?
Have you tried:
is_friend(self, user):
return self.friends.filter(friendship__them=user, friendship__confirmed=True).count()
精彩评论