Search code examples
djangodjango-modelsdjango-serializer

nested serialize Django object


hi guys i want to serialize my model's object. and my model like this :

class User (models.Model):
   name = models.CharField(max_length=30)
   family_name = models.CharField(max_length=30)

and i have another model like this:

class Child (models.Model):
   little_name = models.CharField(max_length=30)
   user = models.ForeignKey("User", on_delete=models.CASCADE,)

i want to serialize one of my child object with all fields in user field for example like this:

{"id": 1 ,
 "little_name": "Sam",
 "user": {"id": 1,
          "name": "Karim",
          "family_name":"Kari"
         }
}

i use model_to_dict() and dict() and serializer of django but i can't get user field compeletly and they return it like this :

{"id": 1 ,
 "little_name": "Sam",
 "user": "id": 1,
}

and i don't want to use django rest serializer what can i do ?!?


Solution

  • Use model_to_dict twice:

    child_dict = model_to_dict(child)
    child_dict['user'] = model_to_dict(child.user)