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?
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.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With