I'm having issues with serializing a list. so my models.py looks like this:
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
and my serializers.py looks like this:
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)
however my json response is formatted wrong, I'm trying to make it
{
"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
}
whats happening is the "cast" part of the json is splitting the cast into multiple characters. for instance it's becoming
"cast": [
"[",
"'",
"B",
"r",
and so on for every character
]
I've tried switching to JSONField, using a ListField for cast in the serializer.py file, using Textfield() for cast in the models. Using SQLite for the db
CodePudding user response:
can you try by change your serialziers to following:
class show_serializer(serializers.ModelSerializer):
class Meta:
model = Show
fileds = '__all__'
and also add ListField in models rather in serializers class
CodePudding user response:
SQLite has limited functionalities so it doesn't support ArrayField or JSONField.
The easiest way is to use SerializerMethodField. But it seems you store the python array directly in your db which is ['Br...sth', 'el2']
.
So you need to change a little bit for better storing:
obj.cast = ','.join(cast_array)
So it will become Br...sth,el2
in your db, then you can parse it to list.
Btw you don't need to define all the fields in your serialier, ModelSerializer will do it for you automatically.
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)