Reverse foreign key relationship in filter

653 views
Skip to first unread message

arlus ishmael

unread,
May 9, 2015, 6:14:43 AM5/9/15
to django...@googlegroups.com
I have three models that look as follows:

class Project(models.Model):
    name = models.CharField(max_length=100)

class ProjectAllocation(models.Model):
    project = models.ForeignKey(Project)
    location = models.ForeignKey(Location)
    
class Location(models.Model):
    name = models.CharField(max_length=50)

I'm writing a filter for the Project model. Is there a way I can include "Location" in my filter??

Carlton Gibson

unread,
May 22, 2015, 10:21:48 AM5/22/15
to django...@googlegroups.com
Hi. 


On Saturday, 9 May 2015 12:14:43 UTC+2, arlus ishmael wrote:

I'm writing a filter for the Project model. Is there a way I can include "Location" in my filter??

 Yes. From the docs:

Items in the fields sequence in the Meta class may include “relationship paths” using Django’s __syntax to filter on fields on a related model:

class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = ['manufacturer__country']

connie.s...@gmail.com

unread,
Feb 3, 2017, 12:25:44 AM2/3/17
to django-filter
Hi Carlton,

further to this issue, if I was filtering on the reverse of Product (so filtering manufacturer by product) would 

fields = ['product_set__name']? Does the '_set' aspect of the django __ syntax hold?

Thank you!

Carlton Gibson

unread,
Feb 3, 2017, 8:38:53 AM2/3/17
to django-filter
Hi Connie. 

First up: have you tried it? (Always a good idea: even if it doesn't work you get an error that tells you something.)

Second: Yes, it should do. 

`product_set` will be the automatically generated reverse relationship. Yes, you can filter across such relationships. 

Kind Regards,

Carlton
Reply all
Reply to author
Forward
0 new messages