Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django filter by two fields rangement

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)
        ]
    )

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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),
        )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading