发送请求正文给序列化器

时间:2019-11-13 08:13:11

标签: python django django-rest-framework

在我的Django项目中,我有以下用于序列化器和视图的

序列化器:

class AnimalSerializer(serializers.ModelSerializer):
    class Meta: 
        model = Animal
        fields = [
            'pk',
            'name',
            'animal_type',
            'weight',
            'color',
        ]

观看次数:

class AnimalRudView(generics.RetrieveUpdateDestroyAPIView): 
    serializer = AnimalSerializer

    def create(self,request):
        body = json.loads(request.body.decode('utf-8')
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM animals WHERE " + body['search'])
            animal = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()]

        return Response(serializer.data)

在视图中,我得到了具有某些条件的请求正文(如“ search”:“ weight> 20”),然后这给了我所有符合这些条件的对象。 我也想将此主体添加到序列化程序中,因为我想自动填充字段列表。 您是否知道如何将正文解析为串行器?

最诚挚的问候

1 个答案:

答案 0 :(得分:0)

以我的自定义post方法之一为例,该方法来自扩展CreateAPIView的类:

class BaseQuestionCheckerView(CreateAPIView):
    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)

        # I can now access the validated data from my
        # serialiser. But first I have to call is_valid():
        try:
           serializer.is_valid(raise_exception=True)
        except Http404:
           raise Http404

        validated_data = serializer.validated_data

        # common thing to do with serializer.validated_data
        # is to return it.

        return Response(serializer.validated_data, status=status.HTTP_200_OK)

希望您能走上正确的轨道!