Django-filter: IsoDateTimeFilter problems comparison other than 'exact'

Created on 14 Sep 2017  ·  3Comments  ·  Source: carltongibson/django-filter

I've been trying to implement the filtering described here: http://django-filter.readthedocs.io/en/develop/ref/filters.html#isodatetimefilter

While that method works, I wanted more than just 'exact' matching, so I replaced:
fields = ['published']
with:
fields = {'published': ['exact', 'gte', 'lte']}
This still works for 'exact' filtering with an IsoDateTime, but for 'gte' and 'lte', it fails when using an IsoDateTime. It works when using a DateTime.

I am using a workaround at the moment which does work with IsoDateTime by specifying each lookup seperately:

published = django_filters.IsoDateTimeFilter(
    name='published', lookup_expr='exact')
published_gte = django_filters.IsoDateTimeFilter(
    name='published', lookup_expr='gte')
published_lte = django_filters.IsoDateTimeFilter(
    name='published', lookup_expr='lte')

Most helpful comment

You can use Meta.filter_overrides to change the filter class used for a model field.

class BookFilter(django_filters.FilterSet):

    class Meta:
        model = Book
        fields = {'published': ['exact', 'lte', 'gte']}
        filter_overrides = {
            models.DateTimeField: {'filter_class': django_filters.IsoDateTimeFilter},
        }

All 3 comments

Hmmm. My first response it to just accept this as a limitation of the dictionary fields syntax. Declaring fields explicitly — your "workaround" — is the canonical way to do it. The dictionary syntax is just a shortcut, and there's no problem with it having limitations.

Having said that, I'd take a change with a small footprint to "fix" this...

You can use Meta.filter_overrides to change the filter class used for a model field.

class BookFilter(django_filters.FilterSet):

    class Meta:
        model = Book
        fields = {'published': ['exact', 'lte', 'gte']}
        filter_overrides = {
            models.DateTimeField: {'filter_class': django_filters.IsoDateTimeFilter},
        }

@carltongibson I'm happy with accepting the limitation. I tried looking for a quick "fix" but my understanding of the inner workings of the code is too limited at the moment :/

@rpkilby Thanks, your suggestion works well, I'll use that going forward :)

@carltongibson Would you like to note this limitation in the docs? I'm happy to make a pull request for it if you think it's appropriate.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

estianross picture estianross  ·  9Comments

mohammadhasanzadeh picture mohammadhasanzadeh  ·  8Comments

loganknecht picture loganknecht  ·  10Comments

KushGoyal picture KushGoyal  ·  10Comments

stantond picture stantond  ·  11Comments