如何在列表API视图中查询SerializerMethodField?

时间:2018-05-24 10:54:58

标签: python django django-rest-framework

我有PhysicalServerListSerializer,其中有一个server_status序列化方法字段。

class PhysicalServerListSerializer(ModelSerializer):

    server_status = serializers.SerializerMethodField()
    class Meta:
        model = PhysicalServer
        fields = "__all__"
        depth = 1

    def get_server_status(self, obj):

        if obj.task and obj.is_finish_task:
            return 'ok'

        if obj.task and not obj.is_finish_task:
            return 'ing'

但是当我在get方法中查询它时,我有一个要求。

http://localhost:8000/api/physicalserver/list/?server_status=ing

它无法查询server_status,如何解决此问题?

我的ListAPIView代码如下:

class PhysicalServerListAPIView(ListAPIView):
    serializer_class = PhysicalServerListSerializer
    permission_classes = [AllowAny]
    pagination_class = CommonPagination

    def get_queryset(self):
        query_params = self.request.query_params
        filters = {'{}__contains'.format(key): value
                   for key, value in query_params.items()
                   }
        qs = PhysicalServer.objects.filter(**filters)
        return qs

1 个答案:

答案 0 :(得分:2)

由于server_status不是模型的字段,因此您无法直接按其值进行过滤。但是,您可以像这样更新您的查询:

def get_queryset(self):
    query_params = self.request.query_params
    filters = {'{}__contains'.format(key): value
               for key, value in query_params.items()
               }
    server_status = query_params.get('server_status')
    if server_status: 
         if server_status == 'ok':
             filters.update({'task__isnull': False, 'is_finish_task': True})        
         if server_status == 'ing':
             filters.update({'task__isnull': False, 'is_finish_task': False})        
    qs = PhysicalServer.objects.filter(**filters)
    return qs

我还建议您使用django-filter。此工具允许您更轻松地实现过滤。但请注意,即使使用django-filter,如果没有server_status自定义,您也无法按FilterSet's实施过滤。