Django filter by two fields rangement

34 views Asked by At

I have a model with two fields: min_age, max_age. And I need to filter it with Django Filters by range of two fields. How can I do that?

# models.py

class AdvertisementModelMixin(models.Model):
    min_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )
    max_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )
1

There are 1 answers

1
willeM_ Van Onsem On BEST ANSWER

You can create a custom filter with:

from django_filters import FilterSet, NumberFilter


class MyFilterSet(FilterSet):
    user_age = NumberFilter(field_name='user_age', method='filter_user_age')

    def filter_user_age(self, queryset, name, value):
        return queryset.objects.filter(min_age__lte=value, max_age__gte=value)

or for nullable's:

from django.db.models import Q
from django_filters import FilterSet, NumberFilter


class MyFilterSet(FilterSet):
    user_age = NumberFilter(field_name='user_age', method='filter_user_age')

    def filter_user_age(self, queryset, name, value):
        return queryset.objects.filter(
            Q(min_age=None) | Q(min_age__lte=value),
            Q(max_age=None) | Q(max_age__gte=value),
        )