简体   繁体   English

无法将字段添加到 serializer.data django rest

[英]Can't add a field to serializer.data django rest

I have a view that displays the project by ID.我有一个按 ID 显示项目的视图。 I want to add one more value into response, but for some reason it is not added.我想在响应中再添加一个值,但由于某种原因没有添加。

class ProjectApiView(APIView):

    def get(self, request, project_id=None):
        if project_id:
            project = Project.objects.get(id=project_id)
            serializer = ProjectSerializer(project)
            serializer.data["all_users"] = 'test'
            print(serializer.data)
            return JsonResponse({'project': serializer.data})
class ProjectSerializer(serializers.ModelSerializer):
    prototype = PrototypeSerializer(read_only=True)

    class Meta:
        model = Project
        fields = ['id', 'name', 'prototype', 'colors']

Serializer.data序列化器.data

{'id': 2, 'name': 'test 2', 'prototype': OrderedDict([('id', 1), ('device_name', 'iphone'), ('width', 900), ('height', 1200), ('image', '/media/blank'), ('image_hover', '/media/blank')]), 'colors': {}}

This is because the .data is a property [GitHub] .这是因为.data是一个属性 [GitHub] What thus happens is that you fetch the value for the .data property, then you manipulate that result, but that is not an object stored at the serializer.因此发生的情况是您获取.data属性的值,然后操作该结果,但这不是存储在序列化程序中的 object。 If you use serializer.data the next time, then again the method behind the property will run, and of course not take into account what happened to the result the previous run.如果下次使用serializer.data ,那么属性后面的方法会再次运行,当然不会考虑上一次运行的结果发生了什么。

You can however simply retrieve the data from the serializer and then alter the outcome of the serializer:但是,您可以简单地从序列化程序中检索数据,然后更改序列化程序的结果

I have a view that displays the project by ID.我有一个按 ID 显示项目的视图。 I want to add one more value into response, but for some reason it is not added.我想在响应中再添加一个值,但由于某种原因没有添加。

class ProjectApiView(APIView):

    def get(self, request, project_id=None):
        if project_id:
            project = Project.objects.get(id=project_id)
            serializer = ProjectSerializer(project)
            result = serializer.data
            result['all_users'] = 'test'
            print(result)
            return JsonResponse({'project': result})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM