简体   繁体   中英

Get data from ManytoMany Relationship

I have the 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 I querying Session.objects.all() , I got the next sample data:

{
  "id_session": "UUID",
  "name": "Example name",
  "speakers": [
    {
      "id_speaker": "UUID",
      "name": "John Doe"
    }
  ]
}

As you see, I have the list of speakers of session, now the question is, how I could got the sessions of speaker, an example that how I want:

{
    "id_speaker": "UUID",
    "name": "John Doe",
    "sessions": [
        {
            "id_session": "UUID",
            "name": "Example name"
        }
    ]
}

If you wondering if I use django-rest-framework, the answer is YES.

eh can't you change the structure of the model?

class Session(models.Model):
    id_session = models.UUIDField(primary_key=True)
    name = models.TextField()


class Speaker(models.Model):
    id_speaker = models.UUIDField(primary_key=True)
    name = models.TextField()
    session = models.ManyToManyField(Session)

Not sure if I understand your question correctly.

Try related_name Django Related Name

Notice the 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 you can get all sessions from a speaker object

some_speaker.sessions.all()  #Returns sessions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM