Search code examples
pythondjangoforeign-keysdjango-filter

django-filter and ForeignKeys


Is there a way to use django-filter with the Foreignkey? For example:

models.py

class Company(models.Model):
    name = models.Charfield(max_length=50, null=False, blank=False)
    location = models.Charfield(max_length=50, null=False, blank=False)


class Person(models.Model):
    first_name = models.Charfield(max_length=50, null=False, blank=False)
    last_name = models.Charfield(max_length=50, null=False, blank=False)
    age = models.Integerfield()
    company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE)

filters.py

class PersonFilter(django_filters.FilterSet):
class Meta:
    model = Person
    fields = [
        'first_name ',
        'last_name ',
        'company ',
    ]

Right now, I only know how to filter for the whole company and often thats's totally fine, but is there a way to - for example - filter for the 'loaction' or any other values as long it's connected with ForeignKey? And if it's not, is there a better solution than django-filter?


Solution

  • Yes! Same as in Django, use the django __ relationship syntax.

    class PersonFilter(django_filters.FilterSet):
    class Meta:
        model = Person
        fields = [
            'first_name ',
            'last_name ',
            'company',
            'company__location',
        ]