BobS
BobS

Reputation: 31

How to base queryset off of current user django rest serializer

I'm trying to create a serializer with DRF that is able to validate if a user has access to a primarykeyrelatedfield entry. I have a separate function which returns a queryset of the files the user can access. All it needs as a parameter is the request object. I'd like to use this function as the queryset kwarg for the primarykeyrelatedfield. However, I can't find a way to access "self" in this location, so there doesn't seem to be a way to define a Queryset which is dependent upon the current user for a serializer.

This is my current attempt, which fails since when calling _request(self) I cannot access self.


class MySerializer(serializers.Serializer):

    def _request(self):
        request = getattr(self.context, 'request', None)
        if request:
            return request


    files = serializers.PrimaryKeyRelatedField(many=True, required=True, queryset=get_user_files(_request(self)))

I want to validate that the user has access to the file(s) they are referencing in the request. How would I do this?

Upvotes: 0

Views: 36

Answers (1)

BobS
BobS

Reputation: 31

I ended up settling on a slightly less clean answer than I'd have liked:

class MySerializer(serializers.Serializer):


    files = serializers.PrimaryKeyRelatedField(many=True, required=True, queryset=ScanFile.objects.all())

    def validate_files(self, value):
        request = self.context.get('request')
        queryset = get_user_files(request)
        for file in value:
            if not queryset.filter(pk=file.id).exists():
                raise ValidationError({'Invalid file': file})
        return value

This seems to be a bit inefficient, as it ends up querying for each file twice, but it achieves the affect of users can only access files they specifically have request to.

Upvotes: 0

Related Questions