How to programmatically provide `queryset` to PrimaryKeyRelatedField in DRF 3

The key is to subclass PrimaryKeyRelatedField and overload the get_queryset method, using the user information from the request context:

class UserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        request = self.context.get('request', None)
        queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset()
        if not request or not queryset:
            return None
        return queryset.filter(user=request.user)

You can then use this new serializer just like the (unfiltered) original:

class MySerializer(serializers.ModelSerializer):
    related = UserFilteredPrimaryKeyRelatedField(queryset=MyModel.objects)

Whenever the serializer accesses the queryset, it will be filtered such that only objects owned by the current user are returned.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)