Django Rest Framework 过滤具有空值和多个值的字段

Django Rest Framework filtering a field with null and multiple values

我正在使用 Django Rest Framework 并希望根据某个字段名称在视图中过滤查询集。

过滤器值将为 null,此外字段 blog_category 的任何其他特定值都是 ForeignKey 值。所以过滤器查询应该在两个查询参数上

class Blog(ListCreateAPIView):
    permission_classes = [DjangoCustomModelPermissions]
    queryset = Blog.objects.all().select_related("blog_category")
    serializer_class = Blog_Serializer
    pagination_class = CustomPageNumberPagination
    filterset_fields = {'blog_category': ['isnull', 'exact', 'in']}

我添加了查找字段isnull来过滤空值

我尝试了以下 url 请求,但它们不起作用

/blog/?blog_catgeory__in=1,null
/blog/?blog_catgeory__in=1,isnull
/blog/?blog_catgeory__in=1,isnull=true
/blog/?blog_catgeory__in=1&blog_category__isnull=true

我如何获得这项工作?

在回答 Javohir Elmurodov 的回答后编辑

我做了以下修改,还是不行

class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
    pass


class BlogFilter(filters.FilterSet):
    blog_category = NumberInFilter(field_name='blog_category', lookup_expr='in')
    blog_category__isnull = BooleanFilter(
        field_name='blog_category', lookup_expr='isnull')


class Blog_ListView(ListData, CreateData, CustomGenericAPIView):
    permission_classes = [DjangoCustomModelPermissions]
    queryset = Blog.objects.all().select_related("blog_category")
    serializer_class = Blog_Serializer
    pagination_class = CustomPageNumberPagination
    filterset_class = BlogFilter

我尝试了以下链接

/blog/?blog_catgeory=1&blog_category__isnull
/blog/?blog_catgeory=1&blog_category__isnull=true

还是不行

我想在查询集中搜索 null OR a particular value in blog_category

的所有条目

将过滤器与其模型字段的类型直接匹配并不总是合适的,因为某些查找需要不同类型的值。这是 inrangeisnull 查找的常见问题。

虽然 category 的基础列类型是 integer,但 isnull 查找需要 boolean 值。

您可以入住Filter and lookup expression mismatch (in, range, isnull)

上面的问题可以通过重写filter方法来解决

from django.db.models import Q
from django_filters import rest_framework as filters
from django_filters import CharFilter

class BlogFilter(filters.FilterSet):
    blog_category = CharFilter(field_name='blog_category_mast',
                               lookup_expr='exact',method='include_null')

    def include_null(self, queryset, name, value):
        return queryset.filter(
            Q(**{f'{name}__isnull': True}) | Q(**{name: value})
        )


class Blog(ListCreateAPIView):
    permission_classes = [DjangoCustomModelPermissions]
    queryset = Blog.objects.all().select_related("blog_category")
    serializer_class = Blog_Serializer
    pagination_class = CustomPageNumberPagination
    filterset_class = BlogFilter