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

To have non-readonly PrimaryKeyRelatedField, you need to provide a query containing valid parameters.

How can I correctly fill out this request based on the current request (user)?

+4
source share
3 answers

You can use request.userin your serializer through the serializer context :

# views.py
class MyView(APIView):

    def post(self, request, *args, **kwargs):
        serializer = MySerializer(data=data, context={'current_user': self.request.user})

Then in your serializer you can access request.userwith:

self.context.get('current_user')
-6
source

The key is to subclass PrimaryKeyRelatedFieldand overload the method get_querysetusing 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)

, () :

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

, , , , .

+18

View has

self.request.user

which can then be used to select a custom set of queries, for example,

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

All Articles