从ManytoMany Relationship获取数据

时间:2017-04-06 01:25:49

标签: python django django-models django-rest-framework

我有以下型号:

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)

当我查询Session.objects.all()时,我得到了下一个样本数据:

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

如您所见,我有会议发言人名单,现在的问题是,我如何能够举办发言人会议,这是我想要的一个例子:

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

如果您想知道我是否使用django-rest-framework,答案是肯定的。

2 个答案:

答案 0 :(得分:0)

呃,你不能改变模型的结构吗?

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)

不确定我是否正确理解了您的问题。

答案 1 :(得分:0)

尝试related_name Django Related Name

注意ManyToManyField中的related_name kwarg

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')

然后你可以从演讲者对象中获取所有会话

some_speaker.sessions.all()  #Returns sessions