dynamically created queryset for PrimaryKeyRelatedField in drf 1

dynamically created queryset for PrimaryKeyRelatedField in drf

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)

Here is what the above code is Doing:
1. We’re creating a new serializer field class that inherits from the built-in PrimaryKeyRelatedField.
2. We’re overriding the get_queryset method to filter the queryset based on the request.user.
3. We’re using this new field class in our serializer.

Similar Posts