2

How can I limit a the queryset of a related field with custom model serialiser based on the request user? I have implemented this with a SerializerMethodField, but it seems not the best solution:

class TourSerializer(serializers.ModelSerializer):
   """
   Returns a list of tour objects.
   """

   orders = serializers.SerializerMethodField()

   class Meta:
      model = Tour
      fields = (
         'id', 'orders'
       )

   def get_orders(self, obj):
       orders = Order.objects.visible_for_me(self.context['request'].user).filter(tour=obj)
       serializer = OrderSerializer(orders, many=True)
       return serializer.data

1 Answer 1

1

You could override the __init__() method of your serializer:

class YourModelSerializer(serializers.ModelSerializer):
    .....
    .....

    def __init__(self, *args, **kwargs):
        super(YourModelSerializer, self).__init__(*args, **kwargs)
        user = self.context['request'].user
        # Limit according to your need, whatever. 
        self.fields['field_name'].queryset = Model.objects.filter(user=user)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the reply. This would limit the queryset of my main model. But I need to limit the queryset for a related model.
You can change the field_name to your related model and limit the queryset.
Or I'm afraid I didn't understand what you were asking. Could you please explain your question with a simple example?
"Nested" fields don't use queryset. Your solution doesn't apply for this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.