Search code examples
djangodjango-filter

How to filter foreign key field by text input in django-filter


I have a City model which contains names of all cities of my country. Also I have Post model with foreign key set to City model. And I created filter to let user filter Posts by city name:

class PostFilter(django_filters.FilterSet):
    class Meta:
        model = Post
        fields = ['city']

And the problem is that, basically foreign key field contains id of related object and filter will find nothing if user inputs actual city name. So, how do I make it so that when user enters city name, it actually works?

Edit:

My models:

class Cities(models.Model):
    name = models.CharField(max_length=63)

class Post(models.Model):
    city = models.ForeignKey(Cities, on_delete=models.RESTRICT, null=True, blank=False)

Solution

  • You can filter with:

    class PostFilter(django_filters.FilterSet):
        city = django_filters.CharFilter(field_name='city__name')
        class Meta:
            model = Post
            fields = []

    You can of course add extra fields on which you wish to filter.