DRF retriveapi view.

Thank you for posting such an interesting problem! This is one of those topics that I wouldn’t ordinarily encounter, and it gave me a great opportunity to learn a lot more about the DRF that I haven’t learned before.

Anyway, I found an answer through a combination of a couple of Stack Overflow answers along with the explanations in a couple of tickets. This ticket was most helpful: https://github.com/encode/django-rest-framework/issues/6938

Anyway, there are two different solutions that I’ve tried in my “experiments” repository that seem to work.

The first, and the one that seems most straight forward to me is a change to the ModelViewSet / ListAPIView

class ParentClassViewSet(ListAPIView):
    queryset = ParentClass.objects.prefetch_related(
        Prefetch('child_class_related_name',
                 queryset=ChildClass.objects.filter(expr=value)
        )
    )
    serializer_class = ParentSerializerClass

The other choice involves creating a custom ListSerializer on the child class with overriding the to_representation method:

class FilteredChildClassList(ListSerializer):
    def to_representation(self, data):
        data = data.filter(query_expression=value)
        return super().to_representation(data)

class ChildClassSerializer(ModelSerializer):
    class Meta:
        list_serializer_class = FilteredChildClassList
        model = ChildClass
        fields = ['list', 'all', 'fields']

class ParentClassSerializer(ModelSerializer):
    related_name = ChildClassSerializer(many=True)
    class Meta:
        model = ParentClass
        fields = ['list', 'of', 'parent', 'class', 'fields', 'including', 'related_name']

I’ve tried both and they both work.

Ken

1 Like