0
class MyFilter(django_filters.FilterSet):
    class Meta:
        model = MyModel
        fields = {
            'field': ['exact',  'isnull'],
        }

Now How do I filter this ?field=1&field__isnull=True ???

4 Answers 4

3

Solved it by adding a custom field.

def filter_field_or_null(queryset, value):
    return queryset.filter(
        Q(field=value) | Q(field__isnull=True)
    )


class MyFilter(django_filters.FilterSet):
    field_or_null = django_filters.ModelChoiceFilter(
        queryset=SomeModel.objects.all(),
        action=filter_field_or_null
    )

    class Meta:
        model = MyModel
Sign up to request clarification or add additional context in comments.

Comments

1

you can view Customize filtering with Filter.method with django-filter 1.1.0, and code can be as below

    class MyFilter(django_filters.FilterSet):
        field = NumberFilter(method='field_exact_or_isnull_filter')

        class Meta:
            model = MyModel
            fields = [field]

        def field_exact_or_isnull_filter(self, queryset, name, value):
            return queryset.filter(
                Q(field=1) | Q(field=None)
            )

Comments

0

I am confused, your question is how to perform OR query, however, your example is "&" (this usually means AND) if you want to make OR condition, you could use Q object

such as:

Q(field=1) | Q(field__isnull=True)

please refer to https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.Q for more information.

Greet.

3 Comments

Can you please answer this in reference to Django-Filter.
@vaibhavjain, sorry, I didn't get your point correctly... it should also use Q object to combine OR condition ...
@zhaorong - it's not entirely clear in the OP, but ?field=1&field__isnull=True is a URL query string. & is just the separator between the key-value pairs.
0

For your reference use Django Filter doc

May be following example useful

from django.db import models
import django_filters

class Mymodel(models.Model):
    field1 = models.CharField(max_length=255)
    field2 = models.IntegerField(null=True)


class MyFilter(django_filters.FilterSet):
    field1__iexact = django_filters.CharFilter(lookup_expr='iexact')
    field1__isnull = django_filters.CharFilter(lookup_expr='isnull')

    class Meta:
        model = Product
        fields = ['field1']

2 Comments

My question is to perform filter on the same field not on different.
So you are saying if I do ?field__iexact=<some_id>&field__isnull= then I will get some_id plus all the null objects ?? I don't think so. As first it will filter the queryset for some_id then for null objects and return the ANed of the query. And I want Or So please see the answer submitted by me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.