python - Get data from ManytoMany Relationship -


i have following models:

class speaker(models.model):     id_speaker = models.uuidfield(primary_key=true)     name = models.textfield()  class session(models.model):     id_session = models.uuidfield(primary_key=true)     name = models.textfield()     speakers = models.manytomanyfield(speaker) 

when querying session.objects.all(), got next sample data:

{   "id_session": "uuid",   "name": "example name",   "speakers": [     {       "id_speaker": "uuid",       "name": "john doe"     }   ] } 

as see, have list of speakers of session, question is, how got sessions of speaker, example how want:

{     "id_speaker": "uuid",     "name": "john doe",     "sessions": [         {             "id_session": "uuid",             "name": "example name"         }     ] } 

if wondering if use django-rest-framework, answer yes.

try related_name django related name

notice related_name kwarg in manytomanyfield

class speaker(models.model):     id_speaker = models.uuidfield(primary_key=true)     name = models.textfield()  class session(models.model):     id_session = models.uuidfield(primary_key=true)     name = models.textfield()     speakers = models.manytomanyfield(speaker, related_name='sessions') 

then can sessions speaker object

some_speaker.sessions.all()  #returns sessions 

Comments