0

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?

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

1

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
Michael Lindsay
  • 1,290
  • 1
  • 8
  • 6