POST json数组并以json数组获取响应

时间:2017-04-26 16:48:27

标签: django django-rest-framework

我的客户端正在向我发送一个带有json-array的POST,正在等待有关所请求数据的完整详细信息的响应。我对单个请求和单个响应没有任何问题,但是为了最小化开销,我想处理一个数组。

my models.py

class RoFile(models.Model):
    user = models.ForeignKey('auth.User', null=True)
    filename = models.CharField(max_length=120, null=True)
    deleted = models.BooleanField(default=False)
    info = models.CharField(max_length=120, null=True)
    md5check = models.CharField(max_length=120, null=True)

我的序列化器的一次尝试:

class RoFileSerializer(serializers.ModelSerializer):
    deleted = serializers.ReadOnlyField(required=False)
    user = serializers.ReadOnlyField(required=False)
    info = serializers.ReadOnlyField(required=False)

    class Meta:
        model = RoFile
        fields = (
            'filename', 'md5check', 'deleted', 'user', 'info',
        )

   def create(self, validated_data):
        return RoFile(**validated_data)

尝试我的观点:

@api_view(['POST'])
def rofile_detaillist(request, format=None):
    data = JSONParser().parse(request)
    serializer = RoFileSerializer(data=data, many=True)
    if serializer.is_valid():
        json_add = []
        for x in serializer.validated_data:
            try:
                rofile = RoFile.objects.filter(md5check=x['md5check'])
            except ObjectDoesNotExist:
                continue

            *invalid code here*

        return Response(jsonarraywithallinfos)
    else:
        return Resonse(status=status.HTTP_400_BAD_REQUEST)

另一种观点尝试:

class RoFileDetailList(viewsets.ModelViewSet):
    model = RoFile
    serializer_class = RoFileSerializer(many=True)

    def get_queryset(self):
         return Rofile.objects.filter(md5check=self.request.data['md5check'])

一个POST示例:

{"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8"},
{"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e"}

作为回复我需要什么:

{"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8", user: "testuser1", deleted: "True", info: ""},
{"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e", user: "testuser1", deleted: "False", info: ""}

对于无效的代码部分感到抱歉,但我已经尝试了很多,所以我删除了那部分(意外)。 谢谢!

修改

我不需要使用POST创建,我只需要检索其他数据(模型的其余部分)。我不得不更改序列化程序中的create函数,因为我不想创建条目,我只想从db中检索与md5check关联的数据。

感谢@ zaphod100.10 我的实际序列化器:

class RoFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoFile
        fields = '__all__'
        read_only_fields = ('deleted',)

    def create(self, validated_data):
        return RoFile(**validated_data)

我的观点:

class RoFileListDetailApi(generics.ListCreateAPIView):
    serializer_class = RoFileSerializer

    def get_queryset(self):
        return RoFile.objects.filter(md5check=self.request.data['md5check'])

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_200_OK, headers=headers)

我的帖子:

{"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8"},
{"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e"}

我的实际响应现在是一个列表,但仅限于我的POST数据而不是db中的实际数据:

{"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8", deleted: false, info: null, user: null},
{"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e", deleted: false, info: null, user: null}

应该是:

{"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8", deleted: true, info: "some info", user: "usertest1"},
{"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e", deleted: false, info: "some info2", user: "usertest2"}

1 个答案:

答案 0 :(得分:0)

使用它:

class RoFileSerializer(serializers.ModelSerializer):

    class Meta:
        model = RoFile
        fields = '__all__'
        read_only_fields = ('deleted', 'user', 'info')

class RoFileListCreateApi(generics.ListCreateAPIView):
    serializer_class = RoFileSerializer

    def get_queryset(self):
         return Rofile.objects.filter(md5check=self.request.data['md5check'])

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        # override perform_create or the serializers create method for custom create logic
        self.perform_create(serializer)
        # assign other fields to the objs and save again
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

您只需将many = True传递给序列化程序即可处理列表。

覆盖通用视图中的perform_create方法或用于应用自定义创建逻辑的序列化器创建方法。

修改

根据提供的新信息,我更改了创建方法。

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data, many=True)
    serializer.is_valid(raise_exception=True)
    # don't create anything just insert required data
    for rof_data in serializer.data:
        md5check = rof_data['md5check']
        # code to retrieve data from db based on md5check
        ....
        # code to insert values in rof_data
        rof_data['user'] = user.username
        rof_data['deleted'] = deleted
        rof_data['info'] = info
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)