Django rest framework - self.context doesn't have request attribute

后端 未结 1 488
无人及你
无人及你 2021-01-07 20:24
class MyModelSerializer(serializers.ModelSerializer):
    field1 = serializers.CharField()
    field2 = serializers.SerializerMethodField(\'get_awesome_user\')

             


        
1条回答
  •  囚心锁ツ
    2021-01-07 21:23

    How do you create serializer in your viewset's list() method? You should call

    serializer = self.get_serializer(data=request.data)
    

    to get your serializer context filled automatically as it is done in default implementation of this method in DRF mixins., but I have a feeling that you're just creating it manually, like this:

    serializer = MyModelSerializer(instance)
    

    So, to fix this, you should either call get_serializer(), or pass extra context argument to serializer constructor:

    serializer = MyModelSerializer(instance, context={'request': request, ...})
    

    0 讨论(0)
提交回复
热议问题