Home > Enterprise >  how to access context in serializer queryset
how to access context in serializer queryset

Time:09-08

I'm looking for a way to access the context to filter by current user

 class RemovePermissionsSerializer(serializers.Serializer):
        user_permissions = serializers.PrimaryKeyRelatedField(
            many=True, queryset=Permission.objects.filter(user = context.get('request').user)
        )

I can't access context becuase it's undefined, neither self.context

CodePudding user response:

In order to achieve that override get_fields method in RemovePermissionsSerializer as shown below:

class RemovePermissionsSerializer(serializers.Serializer):

def get_fields(self):
    fields = super().get_fields()
    # If you want your logic according to request method
    request = self.context.get('request')
    if request and request.method.lower() == "<your method here>":
        fields['user_permissions'] = serializers.PrimaryKeyRelatedField(
            many=True, queryset=Permission.objects.filter(user=request.user)
        )
    
    return fields

If you want to change representation according to the action you can do something like this:

class RemovePermissionsSerializer(serializers.Serializer):

def get_fields(self):
    fields = super().get_fields()
    # IF you want your logic according to action
    view = self.context.get('view')
    if view and view.action == "<action name>":
        fields['user_permissions'] = serializers.PrimaryKeyRelatedField(
            many=True, queryset=Permission.objects.filter(user=request.user)
        )
    return fields

CodePudding user response:

Did you provide the context when initialising the serializer? If you want the context to be available within the Serializer you will have to provide it yourself, like:

serializer = RemovePermissionsSerializer(instance, context={"request": request})

or

serializer = RemovePermissionsSerializer(instance, context={"user": request.user})

That is, the request context is not automatically available in the serializer

  • Related