我有一個像這樣的端點:'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和內容類型「題')。
我曾嘗試:
- 通kwargs到self.get_serializer_context並通過SerializerMethodField得到它,並沒有直接的工作
- 通kwrags到perform_create,但這傳遞DRF側的驗證。
那我該怎麼養活數據從網址到串行? –