Home > other >  Is request available inside django to_representation serializer method?
Is request available inside django to_representation serializer method?

Time:01-25

I am trying to perform a request check inside the to_representation serializer method in django but the self.context is always empty. Any ideas why?

class TwitterAccountsListsSerializer(serializers.ModelSerializer):
    class Meta:
        model = TwitterAccountsList
        fields = ["id", "name", "created_at", "is_private", "accounts"]
        extra_kwargs = {
            "accounts": {"write_only": True},
        }
    
    def to_representation(self, instance):
        import pdb; pdb.set_trace()
        # self.context is always an empty dict here {}
        return super().to_representation(instance)

CodePudding user response:

You need to pass request through serializer context. If you are using Generic Views, and get_serializer function instead of accessing serializer directly, request is passed by default. Otherwise you can pass explicitly like this.

serializer = YouSerializerClass(#other arguments here, context={'request': request})

In generic views like this

serializer = self.get_serializer(# your argument here)

Then you can access that from serializer anywhere like this

request = self.context.get('request')
  •  Tags:  
  • Related