我在Django中有一个序列化程序如下:
class ListSerializer(serializers.HyperlinkedModelSerializer):
vehicles = serializers.HyperlinkedRelatedField(
view_name='asset-detail',
many=True,
read_only=True
)
class Meta:
model = List
fields = ('url', 'name', 'start', 'stop', 'state', 'vehicles')
我得到的结果如下:
[
{
"url": "http://127.0.0.1:8000/sales/api/v1/lists/3741/",
"name": "DEA 2017",
"start": "2017-03-09T10:00:00",
"stop": "2017-12-31T12:00:00",
"state": "OPEN",
"vehicles": [
"http://127.0.0.1:8000/sales/api/v1/assets/134299/",
"http://127.0.0.1:8000/sales/api/v1/assets/154368/",
"http://127.0.0.1:8000/sales/api/v1/assets/154367/",
"http://127.0.0.1:8000/sales/api/v1/assets/154246/",
"http://127.0.0.1:8000/sales/api/v1/assets/155906/",
"http://127.0.0.1:8000/sales/api/v1/assets/155212/",
"http://127.0.0.1:8000/sales/api/v1/assets/154574/",
"http://127.0.0.1:8000/sales/api/v1/assets/155683/",
"http://127.0.0.1:8000/sales/api/v1/assets/153347/",
"http://127.0.0.1:8000/sales/api/v1/assets/153183/",
"http://127.0.0.1:8000/sales/api/v1/assets/153182/",
"http://127.0.0.1:8000/sales/api/v1/assets/153152/",
"http://127.0.0.1:8000/sales/api/v1/assets/153116/",
"http://127.0.0.1:8000/sales/api/v1/assets/154913/",
"http://127.0.0.1:8000/sales/api/v1/assets/152389/",
"http://127.0.0.1:8000/sales/api/v1/assets/153459/",
"http://127.0.0.1:8000/sales/api/v1/assets/153568/",
"http://127.0.0.1:8000/sales/api/v1/assets/153659/"
]
}
]
如果我点击vehicles
中的其中一个网址,我会得到如下对象:
{
"vin": "WVWZZZ6RZEY104640",
"make": "VOLKSWAGEN",
"model": "POLO",
"fuel": "Diesel"
}
我想要的是用对象而不是url来获得结果。
因此如下:
[
{
"url": "http://127.0.0.1:8000/sales/api/v1/lists/3741/",
"name": "DEA 2017",
"start": "2017-03-09T10:00:00",
"stop": "2017-12-31T12:00:00",
"state": "OPEN",
"vehicles": [
{
"vin": "WVWZZZ6RZEY104123",
"make": "VOLKSWAGEN",
"model": "POLO",
"fuel": "Diesel"
},
{
"vin": "WVWZZZ6RZEY10452",
"make": "VOLKSWAGEN",
"model": "Golf",
"fuel": "Diesel"
},
{...},
{...},
{...},
....
]
}
]
有什么建议吗?
P.S。我是初学者,请怜悯:)。
答案 0 :(得分:3)
您正在寻找嵌套的序列化程序,解释为there
答案 1 :(得分:3)
我相信你有一个Vehicle
模型来表示Vehicle属性。
然后,您可以为车辆创建序列化程序,并将其用于List Listizer,如下所示:
class VehicleSerializer(serializers.ModelSerializer):
"""Serializer for vehicle"""
class Meta:
model = Vehicle
class ListSerializer(serializers.HyperlinkedModelSerializer):
vehicles = VehicleSerializer(many=true)
class Meta:
model = List
fields = ('url', 'name', 'start', 'stop', 'state', 'vehicles')