Search code examples
pythondjangodjango-filterdjango-filters

Django Filter using multiple Foreign Keys


I am trying to make a django filter to filter values based on multiple models connected using foreign keys. My models looks like:

model test1(models.Model):
    name=models.CharField()
    ..........some more fields
models test2(models.Model):
    name = models.CharField()
    code  = models.CharField()
models test3(models.Model):
    name = models.CharField()
    code  = models.CharField()
model test4(models.Model):
    first = models.ForeignKey(test1, on_delete=models.CASCADE)
    second = models.ForeignKey(test2, on_delete=models.CASCADE, blank=True, null=True)
    third = models.ForeignKey(test3, on_delete=models.CASCADE, blank=True, null=True)

I want to make a filter from test1 to filter test2 and test3 values. Also, one and only one of the second or third field in model test4 will be null each time.

Currently I was trying to use django_filters but not able to lookup these fields. How can I approach


Solution

  • You can filter a related model with two consecutive underscores (__):

    from django_filters import CharFilter, FilterSet
    
    class ProductFilter(FilterSet):
        first_name = CharFilter(field_name='first__name')
        second_code = CharFilter(field_name='second__code')