Filtering Many-to-Many relationship by Relationshi

2020-02-20 07:46发布

I'm trying to filter many-to-many relationship by some through Class field.

Quoting the Django documentation, i will explain my goal

class Person(models.Model):
      name = models.CharField(max_length=128)

      def __unicode__(self):
          return self.name

class Group(models.Model):
      name = models.CharField(max_length=128)
      members = models.ManyToManyField(Person, through='Membership')

      def __unicode__(self):
          return self.name

class Membership(models.Model):
      person = models.ForeignKey(Person)
      group = models.ForeignKey(Group)
      date_joined = models.DateField()
      invite_reason = models.CharField(max_length=64)

In this example my goal sould be filter many to many relationship and obtain only the Person who has joined some Group starting from certain date (date_joined field).

Is it possible?

1条回答
虎瘦雄心在
2楼-- · 2020-02-20 08:05

You can query across relationships with the django ORM (or in this case the reverse relationship):

person = Person.objects.filter(
    membership__group=example_group,
    membership__date_joined__gte=example_date
)
查看更多
登录 后发表回答