Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 455
alesdario Avatar asked Oct 15 '12 07:10

alesdario


People also ask

How do you do a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


1 Answers

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 ) 
like image 162
Timmy O'Mahony Avatar answered Sep 27 '22 17:09

Timmy O'Mahony