我正在寻找有关如何按值对序列化字段进行排序/分组的建议。 这是一个代码示例,解释了我想要实现的目标。
模型
class Folder(models.Model):
name = models.CharField()
class File(models.Model):
filetype = models.CharField()
name = models.CharField()
folder = models.ForeignKey(Folder)
串行器
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = ('id', 'filetype', 'name')
class FolderSerializer(serializers.ModelSerializer):
files = FileSerializer(read_only=True)
class Meta:
model = Folder
fields = ('name', 'files')
这序列化为:
{
"name": "Test Folder",
"files": [
{"id": 1, "filetype": "pdf", "name": "some pdf file"}.
{"id": 2, "filetype": "pdf", "name": "some other pdf file"},
{"id": 3, "filetype": "txt", "name": "some text file"}
]
}
我正在寻找一种序列化的方法:
{
"name": "Test Folder",
"files": [
"pdf": [
{"id": 1, "name": "some pdf file"},
{"id": 2, "name": "some other pdf file"}
],
"txt": [
{"id": 3, "name": "some text file"}
]
]
}
答案 0 :(得分:4)
尝试使用SerializerMethodField
。你需要实现这样的东西:
class FolderSerializer(serializers.ModelSerializer):
files = serializers.SerializerMethodField()
class Meta:
model = Folder
fields = ('name', 'files')
def get_files(self, obj):
result = {'pdf': [], 'txt':[]}
for file in obj.file_set.all():
serializer = FileSerializer(file)
if file.name.endswith('pdf'):
result['pdf'].append(serializer.data)
if file.name.endswith('txt'):
result['txt'].append(serializer.data)
return result