我在Django Rest Framework序列化程序中覆盖list_serializer_class
。如果我继承了url
,通常我会通过 magic 获得HyperlinkedModelSerializer
字段,但是我需要更改返回所有项目时得到的列表。如果我覆盖list_serializer_class
,则会丢失url
字段。
代码如下:
class CustomOsGroupListSerializer(serializers.ListSerializer):
def to_representation(self, obj):
group = {}
for item in obj:
group[item.id] = {
# I want to add th URL to resource here!
'id': item.id,
'name': item.name,
'os_list': sorted(map(model_to_dict, item.os_list), key=itemgetter('sort_col'))}
return group.values()
class OsGroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.OsGroupOsView
list_serializer_class = CustomOsGroupListSerializer
fields = ('id', 'name', 'os_list', 'url')