Serialize the same model twice

30 views
Skip to first unread message

Harold Achipiz

unread,
Jul 1, 2022, 3:22:30 PMJul 1
to Django users
I am building an API from a model which gives me the following structure

  "user_nucleus_id": 2, 
  "user_id": 2, 
  "nucleus": 2, 
  "family_id": 2, 
  "date": "1974-05-19T19:00:00-05:00" 
}

But now I get the following API structure request. What I understand is that I must serialize the same model twice so that in the "nucleus_users" array it brings me the user id and the family id of the same model.

{
    "user_nucleus_id": 2,
    "user_id": 2,
    "nucleus": 2, 
    "family_id": 2,
    "date": "1974-05-19T19:00:00-05:00", 
    "nucleus_users":[ 
         { 
                   "user_id":"",
                   "family_id":"",
          }
 ], 
}

I would like to know if you can guide me in this special case of how to build this API with this structure from a single model.

Thank you...

models.py
class Usernucleus(models.Model):
user_nucleus_id = models.BigAutoField(primary_key=True)
nucleus = models.ForeignKey(Nucleofamiliar ,on_delete=models.PROTECT)
user = models.ForeignKey(Usuario, on_delete=models.PROTECT)
family = models.ForeignKey(Parentesco, on_delete=models.PROTECT)
date = models.DateTimeField()

serializer.py
class UsernucleusSerializers(serializers.ModelSerializer):

class Meta:
model = Usernucleus
fields = ['user_nucleus_id','user','family','date']
Reply all
Reply to author
Forward
0 new messages