DjangoFilterBackend 字段 = null

Neu*_*ann 5 django-filters django-rest-framework

我将 DjangoFilterBackend 用于所有字段:

class EntitiesViewSet(viewsets.ModelViewSet):
    queryset = Entity.objects.all()
    serializer_class = EntitiesSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend,)
    filter_fields = '__all__'
Run Code Online (Sandbox Code Playgroud)

它非常适合通过具有固定或布尔值的一个或多个字段的 url 进行查询。

像这样:

http://localhost:8000/api/persons/?news_by_email=True
http://localhost:8000/api/persons/?issuer=SSP-SC
Run Code Online (Sandbox Code Playgroud)

但我还需要过滤具有空值的字段,但它不起作用。

我试过:

/persons/?parent=null
/persons/?parent=Null
/persons/?parent=NULL
/persons/?parent=
/persons/?parent__isnull
Run Code Online (Sandbox Code Playgroud)

在同样的简化过程中有什么建议吗?

任何需要扩展或新视图集的建议?

小智 7

除了 isnull 之外,您可能还想查询“精确”值。在这种情况下,

filter_fields = {'parent': ['exact', 'isnull']}
Run Code Online (Sandbox Code Playgroud)

您可以使用 '=True' 进行查询,

/persons/?parent__isnull=True
Run Code Online (Sandbox Code Playgroud)


小智 3

filter_fields = {'parent': ['isnull']}
Run Code Online (Sandbox Code Playgroud)

这将添加一个带有“isnull”的过滤器,您可以进行如下查询:

/persons/?parent__isnull=true
Run Code Online (Sandbox Code Playgroud)

  • 请注意,filter_fields 现在是filterset_fields,但是,这工作正常。如果您还希望能够过滤基础精确值,请添加 [ 'exact', 'isnull' ]。 (2认同)