You can subclass the ListSerializer and overwrite the to_representation
method.
By default the to_representation
method calls data.all()
on the nested queryset. So you effectively need to make data = data.filter(**your_filters)
before the method is called. Then you need to add your subclassed ListSerializer as the list_serializer_class on the meta of the nested serializer.
- subclass ListSerializer, overwriting
to_representation
and then calling super - add subclassed ListSerializer as the meta
list_serializer_class
on the nested Serializer
Here is the relevant code for your sample.
class FilteredListSerializer(serializers.ListSerializer):
def to_representation(self, data):
data = data.filter(user=self.context['request'].user, edition__hide=False)
return super(FilteredListSerializer, self).to_representation(data)
class EditionSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class = FilteredListSerializer
model = Edition
class QuestionnaireSerializer(serializers.ModelSerializer):
edition = EditionSerializer(read_only=True)
company = serializers.StringRelatedField(read_only=True)
class Meta:
model = Questionnaire