synic
synic

Reputation: 26678

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

In order to have a non-readonly PrimaryKeyRelatedField, you are required to provide a queryset that contains valid options.

How can I properly populate that queryset based on the current request (user)?

Upvotes: 33

Views: 12745

Answers (2)

Myk Willis
Myk Willis

Reputation: 12879

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.

Upvotes: 90

Fatima Galaudu
Fatima Galaudu

Reputation: 1

View has a

self.request.user

attribute which you can then use to fetch user related queryset eg

queryset = Products.objects.get(customer=self.request.user)

Upvotes: -13

Related Questions