【发布时间】:2016-11-17 15:37:39
【问题描述】:
在我的应用程序中,我有这个 ModelViewSet 和一个 @list_route() 定义的函数,用于获取列表但使用不同的序列化程序。
class AnimalViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Animal.objects.all()
serializer_class = AnimalSerializer // Default modelviewset serializer
lookup_field = 'this_id'
@list_route()
def listview(self, request):
query_set = Animal.objects.all()
serializer = AnimalListingSerializer(query_set, many=True) // Serializer with different field included.
return Response(serializer.data)
带有此/api/animal/ 端点的默认AnimalViewSet 根据AnimalSerializer 定义产生此序列化数据结果。
{
"this_id": "1001",
"name": "Animal Testing 1",
"species_type": "Cow",
"breed": "Brahman",
...
"herd": 1
},
{
"this_id": "1004",
"name": "Animal Testing 2",
"species_type": "Cow",
"breed": "Holstien",
....
"herd": 1
},
{
"this_id": "1020",
"name": "Animal Testing 20",
"species_type": "Cow",
"breed": "Brahman",
....
"herd": 4
},
另一个是 @list_route() 定义的函数,名为 listview 可能有这个端点 /api/animal/listview/ ,它会产生 AnimalListingSerializer 结构中定义的结果。
{
"this_id": "1001",
"name": "Animal Testing 1",
"species_type": "Cow",
"breed": "Brahman",
....
"herd": {
"id": 1,
"name": "High Production",
"description": null
}
},
{
"this_id": "1004",
"name": "Animal Testing 2",
"species_type": "Cow",
"breed": "Holstien",
....
"herd": {
"id": 1,
"name": "High Production",
"description": null
}
},
{
"this_id": "1020",
"name": "Animal Testing 20",
"species_type": "Cow",
"breed": "Brahman",
....
"herd": {
"id": 4,
"name": "Bad Production",
"description": "Bad Production"
}
}
现在我要做的是定义另一个@list_route() 函数,该函数接受一个参数并使用AnimalListingSerializer 来过滤模型对象的query_set 结果。解决我对像我们这样的初学者的帮助。
@list_route()
def customList(self, request, args1, args2):
query_set = Animal.objects.filter(species_type=args1, breed=args2)
serializer = AnimalListingSerializer(query_set, many=True)
return Response(serializer.data)
让我们假设args1 = "Cow" 和args2 = "Brahman"。我期待这个结果。
{
"this_id": "1001",
"name": "Animal Testing 1",
"species_type": "Cow",
"breed": "Brahman",
....
"herd": {
"id": 1,
"name": "High Production",
"description": null
}
},
{
"this_id": "1020",
"name": "Animal Testing 20",
"species_type": "Cow",
"breed": "Brahman",
....
"herd": {
"id": 4,
"name": "Bad Production",
"description": "Bad Production"
}
},
但我知道我的语法是错误的,但这就是我要说的。 请帮忙。
【问题讨论】:
标签: python django serialization django-rest-framework