Search code examples
pythondjangodjango-filter

Django filter for not null


I have a filter defined as such:

class MessageFilterSet(filters.FilterSet):
    seen = filters.BooleanFilter(field_name="seen_at", lookup_expr="isnull")

And it sort of works. But it's the wrong way around, passing seen=True will return all the unseen messages.

I don't want to have to change the name of the url parameter, how do I invert the lookup expression?


Solution

  • Try this:

    class MessageFilterSet(filters.FilterSet):
        seen = filters.BooleanFilter(field_name="seen_at", lookup_expr="isnull", exclude = True)
    

    From Django Filter Reference Docs:

    exclude

    A boolean that specifies whether the Filter should use filter or exclude on the queryset. Defaults to False.