2017-05-28 44 views
0

我有一個像這樣的端點:'host.com/questions/123/vote'。前端可以發送帶有「向上」或「向下」到這個端點的投票類型的發佈請求。 在後端,投票是這樣的:Django Rest Framework,模型序列化器,使用只讀數據

class Vote(models.Model): 
UP = 'UP' 
DOWN = 'DOWN' 
CHOICE = ((UP, 'upvote'), (DOWN, 'downvote')) 
post_content_type = models.ForeignKey(ContentType, 
             on_delete=models.CASCADE) 
post_id = models.PositiveIntegerField() 
post = GenericForeignKey('post_content_type', 'post_id') 
voter = models.ForeignKey(to=settings.AUTH_USER_MODEL, 
          related_name='votes') 
type = models.CharField(choices=CHOICE, max_length=8) 

class Meta: 
    unique_together = ('post_content_type', 'post_id', 'voter') 

我使用通用的FK,因爲你可以投票給不同的模型實例除了問題了。

現在我使用DRF的CreateAPIView創建此api端點。

這裏是我的問題:

我如何在數據傳遞從兩個來源:request.data(其中投類型),以及kwargs(其中的問題ID和內容類型「題')。

我曾嘗試:

  1. 通kwargs到self.get_serializer_context並通過SerializerMethodField得到它,並沒有直接的工作
  2. 通kwrags到perform_create,但這傳遞DRF側的驗證。

回答

0

您需要爲post_content_type和post_id指定一些write_only字段。

class VoteSerializer(serializers.Serializer): 
    post_content_type_id = serializers.PrimaryKeyRelatedField(write_only=True) 
    post_id = serializers.IntegerField(write_only=True) 
    type = serializers.CharField() 
    ## your other fields ... 

如果您想了解如何爲通用的關係輸出不同的表現,看看在DRF本節文檔:http://www.django-rest-framework.org/api-guide/relations/#generic-relationships

+0

那我該怎麼養活數據從網址到串行? –

0

我結束了覆蓋在串行的to_internal功能,並通過覆蓋在CreateAPIViewget_serializer_context通過URL數據,並在to_internal功能得到使用self.context數據

相關問題