В моем приложении у меня есть ModelViewSet
с одной @list_route()
определенной функцией для получения списка, но с другим сериализатором.Как определить @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
},
А другой, который является @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"
}
},
Но я знаю, что мой синтаксис не так, но это то, что я имею в виду. Пожалуйста, помогите.
Это было ясно и великий человек! –