如何过滤列表属性的长度为“0”?

时间:2018-05-28 06:54:05

标签: python django django-rest-framework

我有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

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)