Django ManyRelatedManager 基于通过类的过滤
我有一个基于直通类的简单的多对多关系。
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)
简而言之,这应该允许某人将其他人添加为朋友,但在其他人确认之前链接不存在。够简单的。
我想向 Person
添加一个 is_friend(self, user)
方法。我想做一些类似的事情:
is_friend(self, user):
return self.friends.filter(them=user, confirmed=True).count()
但是 filter
似乎只对远程类(在本例中 Person
)上进行操作。有什么方法可以在仍然使用 ManyRelatedManager
的同时过滤 Friendship
吗?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有点生疏了,但是你尝试过
return Friendship.objects.filter(me=self,them=user,confirmed=True)
吗?I'm a bit rusty, but have you tried
return Friendship.objects.filter(me=self, them=user, confirmed=True)
?你有没有尝试过:
Have you tried: