Filtering Many-to-Many relationship by Relationship field in Django

alesdario picture alesdario · Oct 15, 2012 · Viewed 13.1k times · Source

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?

Answer

Timmy O'Mahony picture Timmy O'Mahony · Oct 15, 2012

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
)