我有一个像这样的端点:'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侧的验证。
那我该怎么养活数据从网址到串行? –