Reputation: 111
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
Upvotes: 0
Views: 753
Reputation: 1
Another option is to fabricate the serializer with a method, something like:
def get_remove_permission_serializer(user):
class RemovePermissionsSerializer(serializers.Serializer):
user_permissions = serializers.PrimaryKeyRelatedField(
many=True, queryset=Permission.objects.filter(user = user)
)
return RemovePermissionsSerializer
I think it is way cleaner than the accepted answer, but it might be an anti-pattern
Upvotes: 0
Reputation: 223
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
Upvotes: 5
Reputation: 200
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
Upvotes: 0