我试图了解未指定视图集 filterset_fields
中指定的字段会发生什么。我的观点如下:
class DetectionTrainingViewSet(
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet
):
queryset = Detection.objects.all()
serializer_class = DetectionSerializer
filterset_fields = (
'annotation_set__annotator__id',
'annotation_set__bbox__annotator__id',
)
我正在进行以下 GET 调用我的端点 http://127.0.0.1:8000/api/v1/detections/:
?annotation_set__annotator__id=2
-> 我得到 4 个结果?annotation_set__annotator__id=2&annotation_set__bbox__annotator__id=2
-> 我得到 16 个结果,我预计第二次调用会返回下一次调用的子集。这里发生了什么事?如何指定当未明确指定参数时,任何 value (如果不存在)应与查询匹配?
回答1
在这里添加,因为这对于评论来说太长了:
这不应该发生,这些字段应该是 and
ed,根据我的经验,它们是。从您提供的代码中,我看不出为什么这不起作用。
- 总共有多少条记录
- 你能在服务器端看到收到的确切请求吗?
- 您究竟是如何发送此请求的?命令行?浏览器?
我唯一能想到的是查询字符串在发送之前被破坏(可能是通过对其进行urlencoding)。
这是一些简单的 print()
调试,您可以添加到视图集中以在各个点进行检查,而无需附加调试器。
# add this to print the actual query text before & after filtering
def filter_queryset(self, queryset):
print("[before]", queryset.query)
queryset = super().filter_queryset(queryset)
print("[after ]", queryset.query)
return queryset
# add this override to see what your path / qs / etc are
def list(self, request, *args, **kwargs):
print(request.path)
print(request.META["QUERY_STRING"])
print(request.query_params)
return super().list(request, *args, **kwargs)