2015-12-28 26 views
2

這是我的(簡化的)models.py:'RelatedManager' 對象在DRF沒有屬性 'pk' 中串行

class MyList(models.Model): 
    title = models.CharField(max_length=40) 
    participants = models.ManyToManyField(
     settings.AUTH_USER_MODEL, 
     through='ParticipantsInList', 
     related_name='participants', 
    ) 

class ParticipantsInList(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user') 
    list_parent = models.ForeignKey(MyList, related_name='list_parent') 
    moderator = models.BooleanField(default=False) 

和我的serializers.py:

class ParticipantsInListSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = ParticipantsInList 
     exclude = ('id',) 

和我的views.py:

​​

我想不通爲什麼在views.py使用此:ParticipantsInList.objects.filter(LIST_ID = LIST_ID)作品,同時採用List.objects.get(PK = LIST_ID).participants.all ()引發異常'RelatedManager'對象沒有屬性'pk'。

我想使用後者,因爲我覺得它好看,還因爲我認爲它應該工作..

+2

我不知道發生了什麼究竟怎麼回事,但你不應該使用'list'作爲模型的字段名稱,因爲它保留爲內置關鍵字的python。如果你這樣做,它可能會導致很多問題。 –

+0

謝謝,我現在改變了它。然而,這個問題在這個特殊情況下與這個問題沒有關係。儘管我設法解決了這個問題,但如果您有興趣,可以在下面找到答案。 –

回答

4

的問題是,我試圖序列化,通過模型,如果查詢其作品運行在直通模式本身上(如使用過濾器時的情況)。但是當使用MyList中的ManyToManyField進行查詢時,只返回實際的用戶對象。因此,在引用ManyToManyField時,解決方案是使用可序列化用戶對象的序列化程序,而不是直通模型。

運行在一個殼體中的查詢使這個顯而易見的:

> ParticipantsInList.objects.filter(list_parent=1) 
[<ParticipantsInList: ParticipantsInList object>, <ParticipantsInList: ParticipantsInList object>] 

儘管正在運行的其他查詢返回:

> MyList.objects.get(pk=1).participants.all() 
[<MyUser: user1>, <MyUser: user2>] 
+1

謝謝,非常有幫助 - 不確定它是否適用於這種情況,但我需要使用'many = True'調用嵌套序列化器 – ptim

相關問題