【问题标题】:How to serialize a list of string using Listfield in DRF如何使用 DRF 中的 Listfield 序列化字符串列表
【发布时间】:2019-07-23 18:06:01
【问题描述】:

我正在尝试使用 DRF ListField 存储关键字列表。我能够发布正确保存在数据库中的关键字列表。但是当我使用 GET 请求检索列表时,我得到一个字符列表而不是预期值。

这是我的看法:

class profile(APIView):

    renderer_classes = [JSONRenderer]
    serializer_class = ProfileSerializer

    def get(self, request):
        serializer = self.serializer_class(request.user.profile)
        return Response(serializer.data, status=200)

    def post(self, request):
        serializer_data = request.data
        serializer = self.serializer_class(request.user.profile, data=serializer_data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=200)

这是我的序列化器:

class ProfileSerializer(serializers.ModelSerializer):
    keywords = serializers.ListField(child=serializers.CharField(allow_blank=True))


The POST request looks like this:

    {"keywords":["keyword1", "keyword2", "keyword3"]}

POST works fine but when I try to GET the values I get a list like this:

    "keywords": [
        "[",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "1",
        "'",
        ",",
        " ",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "2",
        "'",
        ",",
        " ",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "3",
        "'",
        "]"
    ]

【问题讨论】:

    标签: django-rest-framework serialization listfield


    【解决方案1】:

    你可以这样做:

    keywords = json.loads(request.data['keywords'])}    
    serializer = self.serializer_class(
        request.user.profile, data={'keywords': keywords}, partial=True
    )
    

    然后在serializer.validated_data 中,您将拥有{"keywords":["keyword1", "keyword2", "keyword3"]}

    也许它看起来不太好,但是使用 json.loads() 你会得到 python 列表而不是你试图序列化的字符串。

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 2018-04-20
      • 2018-06-29
      • 1970-01-01
      • 2017-11-09
      • 2023-02-10
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      相关资源
      最近更新 更多