在序列化程序中过滤嵌套查询集
Filter nested queryset in serializer
我有这些型号:
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
当我调用 FolderViewSet
LIST 请求时,它为每个 Folder
序列化了所有 Files
。我需要让它只序列化成为特定 Item
.
的文件
现在,我正在前端过滤 Files
,但将来会变得非常重量级。
你知道如何让它发挥作用吗?有内置的方法吗?
SerializerMethodField 允许添加自定义查询来限制外键模型。
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
我有这些型号:
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
当我调用 FolderViewSet
LIST 请求时,它为每个 Folder
序列化了所有 Files
。我需要让它只序列化成为特定 Item
.
现在,我正在前端过滤 Files
,但将来会变得非常重量级。
你知道如何让它发挥作用吗?有内置的方法吗?
SerializerMethodField 允许添加自定义查询来限制外键模型。
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