python django rest框架返回不正确的响应格式

nimxete2  于 2023-02-02  发布在  Python
关注(0)|答案(2)|浏览(99)

我在序列化列表时遇到了问题,所以我的models.py看起来像这样:

class Show(models.Model):     
    name = models.CharField(max_length = 500)     
    rating = models.FloatField()     
    network = models.CharField(max_length = 500)     
    description = models.CharField(max_length = 500)     
    episodes = models.IntegerField()     
    cast = models.CharField(max_length=200)     
    rating = models.FloatField()
    def __str__(self):return self.name

我的serializers.py是这样的

class show_serializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only = True) 
    name = serializers.CharField() 
    network = serializers.CharField() 
    description = serializers.CharField() 
    episodes = serializers.IntegerField() 
    cast = serializers.ListField(child=serializers.CharField(max_length=100)) 
    rating = serializers.FloatField()

    def create(self, data):
        return Show.object.create(****data)

然而我的json响应格式错误,我正在尝试使它

{
            "id": 3,
            "name": "Breaking Bad",
            "description": "A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family's future.",
            "network": "AMC",
            "episodes": 62,
            "cast": [
                "Bryan Cranston",
                "Aaron Paul",
                "Anna Gunn",
                "Dean Norris"
            ],
            "rating": 9.5
        }

所发生的是json的“cast”部分正在将cast分割成多个字符。例如,它正在成为

"cast": [
"[",
"'",
"B",
"r",
and so on for every character
]

我试过切换到JSONField,在www.example.com文件中使用ListField进行转换serializer.py,在模型中使用Textfield()进行转换。

kpbwa7wx

kpbwa7wx1#

你可以尝试通过改变你的序列化器如下:

class show_serializer(serializers.ModelSerializer):
    class Meta:
        model = Show
        fileds = '__all__'

并在模型中而不是在序列化程序类中添加ListField

fivyi3re

fivyi3re2#

SQLite功能有限,因此不支持ArrayField或JSONField。
最简单的方法是使用SerializerMethodField,但是似乎你直接把python数组存储在你的数据库['Br...sth', 'el2']中,所以为了更好地存储,你需要做一些修改:

obj.cast = ','.join(cast_array)

所以它在你的数据库中会变成Br...sth,el2,然后你可以把它解析成list。
顺便说一句,你不需要在你的序列化器中定义所有的字段,ModelSerializer会自动为你做这件事。

import json

class show_serializer(serializers.ModelSerializer):
    cast = serializers.SerializerMethodField() 

    def get_cast(self, obj):
        return obj.cast.split(',')

    def create(self, data):
        return Show.object.create(****data)

相关问题