使用Django RestFramework将JSON平面嵌套到Jested

时间:2018-06-10 03:37:36

标签: django django-rest-framework django-serializer

我的观点中有一个json,如下所示,

{
"name":"myname",
"age":30,
"day":20,
"month":"June",
"year":1988
}


如何使用Serializers ?,

将其转换为嵌套的JSON,如下所示
{
"name":"myname",
"age":30,
"DOB":{
    "day":20,
    "month":"June",
    "year":1988
    }
}

2 个答案:

答案 0 :(得分:2)

如果我没错,你必须定义两个序列化程序类,如下所示:

from rest_framework import serializers

class MyNestedSerializer(serializers.Serializer):
    day = serializers.IntegerField()
    month = serializers.CharField()
    year = serializers.IntegerField()

class MyBasicSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.IntegerField()
    DOB = MyNestedSerializer(source='*')

然后您将获得嵌套数据:

nested_json = MyBasicSerializer(my_flat_input).data

source='*'具有特殊含义,用于指示整个对象应该传递到字段。这对于创建嵌套表示或者需要访问整个对象以确定输出表示的字段非常有用。

参考:

  1. source in DRF Serializer
  2. SO-Post

答案 1 :(得分:2)

@ No-One ,假设您已按如下方式定义模型。

  

http://www.django-rest-framework.org/api-guide/relations/

     

{'day': 20, 'month': 'June', 'year': 1998}这样的嵌套词典使用 ForeignKey()

class Dob(models.Model):
    day = models.IntegerField()
    month = models.CharField(max_length=10)
    year = models.IntegerField()

    def __str__(self):
        return str(self.day)

class User(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)
    age = models.IntegerField()
    dob = models.ForeignKey(Dob, on_delete=models.CASCADE, null=False)

    def __str__(self):
        return self.name

enter image description here

enter image description here

然后我建议您像这样定义序列化器。

  

如果您有疑问,请发表评论。

class DobSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dob 
        fields = ('day', 'month', 'year')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    dob = DobSerializer(many=False, read_only=True);

    class Meta:
        model = User
        fields = ('name', 'age', 'dob');

enter image description here