【发布时间】:2017-10-29 00:36:17
【问题描述】:
我有一个这样的端点:'host.com/questions/123/vote'。前端可以向该端点发送投票类型为“上”或“下”的帖子请求。 在后端,投票是这样的:
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,因为除了 Question 之外,您也可以投票给不同的模型实例。
现在我使用 DRF 的 CreateAPIView 创建了这个 api 端点。
这是我的问题:
我如何从两个来源传递数据:request.data(投票类型在哪里)和 kwargs(问题 ID 和内容类型“问题”在哪里)。
我试过了:
- 将 kwargs 传递给 self.get_serializer_context 并通过 SerializerMethodField 获取,不起作用
- 直接将 kwrags 传递给 perform_create,但这会通过 drf 端的验证。
【问题讨论】:
标签: django django-rest-framework