3

I've got a json in my view as below,

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


How can I convert it to a nested JSON as below using Serializers?,

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

1 Answers1

1

@No-One, Let suppose you have defined your models as follows.

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

Use ForeignKey() for nested dictionary like {'day': 20, 'month': 'June', 'year': 1998}.

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

Then I'll suggest you to define your serializers like this.

Please comment, if you've queries.

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

Community
  • 1
  • 1
hygull
  • 8,464
  • 2
  • 43
  • 52
  • 1
    The original post says, the input is a `JSON`, not any Model instances – JPG Jun 11 '18 at 04:11
  • As I understood, in case of **@No-one** view means the view that we can see in the 3rd image, and **@No-one** wants this presentation of JSON rather than the one that originally he/she gets. – hygull Jun 11 '18 at 04:25