在我的应用程序中,我有zfs clone
个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)
终点的默认AnimalViewSet
会根据/api/animal/
定义生成此序列化数据结果。
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
},
的{{1}}定义函数可能有此终点@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"
但我知道我的语法错了,但这就是我所说的。 请帮忙。
答案 0 :(得分:2)
视图函数中的参数是为URL引用保留的。即路由animals / 5将被传递给具有pk作为参数的视图函数。
def get(self, request, pk):
# get animal with pk
return animal with pk
您可以通过查询参数将参数传递到您的网址,即
/animals/listview/?speceis_type=cow&breed=braham
然后使用请求对象在您的视图中访问它
request.query_params['speceis_type']
和request.query_params['braham']
或者您可以使用记录为here的django rest过滤器中间件