Django模型ManyToMany反向过滤器

Django模型ManyToMany反向过滤器

本文介绍了Django模型ManyToMany反向过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的模型的摘录:

Here's excerpts from (something analogous to) my models:

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类中构建一个新方法:

If I want to see who a given person is following, I can build a new method into the Person class:

def get_following(self):
  return self.relationships.filter(
    to_people__status='Following',
    to_people__from_person=self)

这有效:

>>> p2.get_following()
<QuerySet [<Person: C>]>

我想做相反的事情.我要问的是谁跟随这个人?",而不是问这个人跟随谁?".我可以这样做(尽管它返回Relationship对象,而不是Person对象):

I want to do the REVERSE of this. Instead of asking "Who does this person follow?", I want to ask "Who follows this person?". I can do that like this (although it returns Relationship objects, not Person objects):

>>> Relationship.objects.filter(to_person=p3, status='Following')
<QuerySet [<Relationship: B is Following to C>]>

我的尝试是这样(返回一个空的QuerySet):

My attempt is this (which returns an empty 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')

推荐答案

这是我选择的答案:

def get_followers(self):
  return self.related_to.filter(from_people__status='Following')

这篇关于Django模型ManyToMany反向过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:31