我具有如下所示的当前api,我的目的是使其显示所需的输出。我想将年龄和国籍(如下所示)(请参阅所需的输出)添加到嵌套的类型中,但是它似乎仅以不嵌套的纯格式显示。使其嵌套的最佳方法是什么?
"type" : [
{ "age" : "27", "nationality" : "usa" }
当前API
[
{
"name" : "Jay",
"school" : "college",
"type" : "usa"
"age": "27"
"nationality": "usa"
},
]
所需的API
[
{
"name" : "Jay",
"school" : "college",
"type" : [
{ "age" : "27", "nationality" : "usa" },
{ "age" : "24", "nationality" : "canada" },
{ "age" : "26", "nationality" : "thailand" },
]
}
]
Serializers.py
class SchoolSerializer(serializers.ModelSerializer):
class Meta:
model = School
fields = ("name", "school", "type", "age", "nationality")
def update(self, instance, validated_data):
instance.name = validated_data.get("name", instance.name)
instance.school = validated_data.get("school", instance.session)
instance.type = validated_data.get("type", instance.session)
instance.age = validated_data.get("age", instance.session)
instance.nationality = validated_data.get("nationality", instance.session)
instance.save()
return instance
models.py
class School(models.Model):
name = models.CharField(max_length=255, null=False)
school = models.CharField(max_length=255, null=False)
type = models.CharField(max_length=255, null=False)
age = models.CharField(max_length=255, null=False)
nationality = models.CharField(max_length=255, null=False)
def __str__(self):
return "{} - {}".format(self.name, self.school)
views.py
class ListSchoolView(generics.ListCreateAPIView):
"""
Provides a get method handler.
"""
queryset = School.objects.all()
serializer_class = SchoolSerializer
答案 0 :(得分:1)
如果要自定义模型的序列化方式,请覆盖序列化器的to_representation
方法。这似乎与REST API设计背道而驰,因此我不建议这样做。您应该为TypeSerializer创建一个单独的序列化程序,以获得最佳结果。
将此方法添加到SchoolSerialzer中以实现所需的格式:
def to_representation(self, obj):
rep = super().to_representation(obj)
age = rep.pop('age')
type_ = rep.pop('type')
rep['type'] = {
'age': age,
'nationality': type_
}
return rep