Filter nested queryset in serializer

41 views Asked by At

I have these models:

    class Item(..):
        ....

    class Folder(..):
        ...

    class File(..):
        item = ...
        folder = ...

class FileSerializer(...):
    class Meta:
        model = File

class FolderSerializer(...):
    files = FileSerializer(many=True,readonly=True)
    class Meta:
        model = Folder

When I call the FolderViewSet LIST request, it serialized all the Files for every Folder. I need to make it serialize only files that became to the particular Item.

Right now, I'm filtering the Files on the frontend but that will become very heavyweight in a future.

Do you know how to make it work? Is there a built-in way?

1

There are 1 answers

0
Michael Lindsay On BEST ANSWER

The SerializerMethodField allows adding a custom query to restrict foreign key models.

class FolderSerializer(...):
    files = serializers.SerializerMethodField()

    class Meta:
        model = Folder

    def get_files(self, instance):
        files = File.objects.filter(folder=instance)
        serializer = FileSerializer(instance=files, request=request, many=True, readonly=True)
        return serializer.data