Search code examples
djangodjango-rest-frameworkdjango-filter

Meta.filter_overrides for IntegerRangeField in django filter view


Using the example in the Django documentation for utilizing IntergerRangeField with Postgres backend to create ranges in "ages" with the following model:

from django.contrib.postgres.fields import IntegerRangeField
from psycopg2.extras import NumericRange

from django.db import models

class Event(models.Model):
    name = models.CharField(max_length=200)
    ages = IntegerRangeField()

    def __str__(self):  
        return self.name

This works perfectly however when using Django Rest Frameworks and using filter view with the following filter:

import django_filters
from django_filters import rest_framework as filters
from app import Event

class EventFilter(django_filters.FilterSet):
ages = django_filters.NumericRangeFilter(queryset=Event.objects.all())
class Meta:
    model = Event
    fields = ['name','ages']

the view generates an AssertionError at /api/event_filter/ and suggests adding an override to Meta.filters_override. What I would really appreciate is an example based on the example model for this override, the example in django-filters documentation http://django-filter.readthedocs.io/en/latest/ref/filterset.html#filter-overrides, isn't helping me understand how to get this to render. I would appreciate any help with this so I can understand with this example to utilize this in the future.


Solution

  • Based on the documentation, overriding custom option seems to be done inside the Meta class and not the way you have done it. ages = django_filters.NumericRangeFilter(queryset=Event.objects.all())

    There are a few potential issues here:

    1. The declaration itself does not seem supported
    2. The overrides appear to be supported from within the Meta class
    3. queryset is not a valid option for NumericRangeFilter AFAIk

    Can you try the following:

    from django.contrib.postgres.fields import IntegerRangeField
    
    class EventFilter(django_filters.FilterSet):
        class Meta:
            model = Event
            fields = ['name','ages']
            filter_overrides = {
                 IntegerRangeField: {
                     'filter_class': django_filters.NumericRangeFilter,
                 }
            }