Django REST Framework: how serializer context works?

后端 未结 2 1191
-上瘾入骨i
-上瘾入骨i 2021-02-13 14:31

It\'s a pretty standard task in Django REST Framework to supply additional args/kwargs to a serializer to set values of fields set not via reques

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 14:53

    to set values of fields set not via request.data, but via the value in url parameters or cookies. For instance, I need to set user field of my Comment model equal to request.user upon POST request.

    This is how I handle both cases in my ModelViewSet:

    def perform_create(self, serializer):
    
        # Get article id from url e.g. http://myhost/article/1/comments/
        # obviously assumes urls.py is setup right etc etc
        article_pk = self.kwargs['article_pk']
        article = get_object_or_404(Article.objects.all(), pk=article_pk)
    
        # Get user from request
        serializer.save(author=self.request.user, article=article)
    

    Unfortunately the nested objects is not standard for DRF but that's besides the point. :)

提交回复
热议问题