我有ListAPIView
,这是访问网址localhost:8000/api/physicalserver_task/list
的结果:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 16,
"physicalservers": [],
...
代码如下:
class PhysicalServerTaskListForHomeWorkPanelAPIView(ListAPIView):
serializer_class = PhysicalServerTaskListForHomeWorkPanelSerializer
permission_classes = [IsAdminUser]
pagination_class = CommonPagination
def get_queryset(self):
filters = {'{}__contains'.format(key): value
for key, value in query_params.items()}
return PhysicalServerTask.objects.filter(**filters)
我有一个要求,即过滤physicalservers
的长度为0
。
你知道如果我们只是过滤id
,我们可以使用
localhost:8000/api/physicalserver_task/list/?id=16
但是,如果我想过滤physicalservers
的计数是0
怎么样?
修改-1
我的Serialiazer代码如下:
class PhysicalServerTaskListForHomeWorkPanelSerializer(ModelSerializer):
physicalservers = PhysicalServerTaskSerializer(many=True, read_only=True)
physicalserver_count = serializers.IntegerField(write_only=True, allow_null=True)
class Meta:
model = PhysicalServerTask
fields = "__all__"
depth = 1
答案 0 :(得分:1)
您可以使用phisicalservers__isnull
查找:
def get_queryset(self):
filters = {'{}__contains'.format(key): value
for key, value in query_params.items()}
if query_params.get('serverscount') == 0:
filters.update({'phisicalservers__isnull': True})
return PhysicalServerTask.objects.filter(**filters)