Reputation: 18745
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?
Upvotes: 0
Views: 44
Reputation: 1355
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
Upvotes: 1