【发布时间】:2018-01-12 00:56:36
【问题描述】:
以下是(类似于)我的模型的摘录:
class Person(models.Model):
name = models.CharField(max_length=20)
relationships = models.ManyToManyField('self',
through='Relationship',
symmetrical=False,
related_name='related_to',
)
def __str__(self):
return self.name
class Relationship(models.Model):
from_person = models.ForeignKey(Person,
related_name='from_people',
on_delete=models.CASCADE,
)
to_person = models.ForeignKey(Person,
related_name='to_people',
on_delete=models.CASCADE,
)
status = models.CharField(max_length=20)
def __str__(self):
return "{} is {} {}".format(
self.from_person.name, self.status, self.to_person.name)
这是我的数据库的内容:
>>> Person.objects.all()
<QuerySet [<Person: A>, <Person: B>, <Person: C>]>
>>> Relationship.objects.all()
<QuerySet [<Relationship: B is Following C>]>
如果我想查看某个特定的人在关注谁,我可以在 Person 类中构建一个新方法:
def get_following(self):
return self.relationships.filter(
to_people__status='Following',
to_people__from_person=self)
这行得通:
>>> p2.get_following()
<QuerySet [<Person: C>]>
我想做这个的反向操作。与其问“这个人关注谁?”,我想问“谁关注这个人?”。我可以这样做(尽管它返回的是关系对象,而不是个人对象):
>>> Relationship.objects.filter(to_person=p3, status='Following')
<QuerySet [<Relationship: B is Following to C>]>
我的尝试是这样的(它返回一个空的 QuerySet):
def get_following(self):
return self.relationships.filter(
from_people__status='Following',
from_people__to_person=self)
感谢您的帮助!
编辑: 这是我选择的答案:
def get_followers(self):
return self.related_to.filter(from_people__status='Following')
【问题讨论】:
-
你想从人那里,还是向人,还是所有人?
-
关注给定人员的所有人员的查询集。
标签: python django filter manytomanyfield