2017-04-06 72 views
0

我有以下型號:從多對多的關係獲取數據

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,答案是YES。

回答

0

嘗試related_nameDjango Related Name

通知的related_name kwarg在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') 

然後你就可以得到所有會話從揚聲器對象的回答

some_speaker.sessions.all() #Returns sessions 
+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) 

不知道我是否正確理解你的問題。