如何将用户从请求隐式传递到相应的序列化程序?

时间:2018-01-18 08:19:23

标签: django django-rest-framework

我有以下代码:

class Article(models.Model):
    ...
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content', 'owner')
        extra_kwargs = {
            'owner': {'write_only': True},
        }

class ArticleList(generics.ListCreateAPIView):
    serializer_class = ArticleSerializer

    def get_queryset(self):
        user = self.request.user
        return Article.objects.filter(owner=user.id)

    def post(self, request, *args, **kwargs):
        request.data['owner'] = self.request.user.id
        return self.create(request, *args, **kwargs)

我必须在ArticleList ApiView的post方法中明确地传递用户来满足ForeignKey非空要求。这可以。但我有另一个带有ForeignKey的模型到User,因此它会导致许多复制粘贴行,特别是在POST和PUT方法中。 有人知道更优雅的DRY解决方案吗?

0 个答案:

没有答案