我有模特:图书馆可以有很多书。
现在我有一个用于在特定库中的书籍上执行CRUD的URL:
router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet, base_name='books')
和相应的观点:
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
def get_queryset(self):
genre_query = self.request.query_params.get('genre', None)
status_query = self.request.query_params.get('status', None)
author_query = self.request.query_params.get('author', None)
books = Book.objects.filter(which_library=self.kwargs.get('library_id'))
if genre_query:
books = books.filter(genre=genre_query)
if status_query:
books = books.filter(status=status_query)
if author_query:
books = books.filter(author=author_query)
return books
我最初没有使用ModelViewSet,而是使用了@api_view装饰器的功能,其中一个是跟随的(返回过去两周添加的书籍,我有一个单独的URL作为api / books // new_arrivals这个函数):< / p>
@api_view(['GET'])
def new_arrivals(request, library_id):
"""
List all new arrival books in a specific library
"""
d=timezone.now()-timedelta(days=14)
if request.method == 'GET':
books = Book.objects.filter(which_library=library_id)
books = books.filter(when_added__gte=d)
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
使用ModelViewSets时,我该怎么办?我必须添加另一个URL,然后为new_arrivals编写另一个类或在现有的BookViewSet中编写一个函数吗?在这种情况下如何实现处理这两种GET方法?
答案 0 :(得分:2)
您可以通过添加特殊方法 public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
context.Logger.LogLine("Get Request\n");
var path = "none";
if (request.PathParameters != null && request.PathParameters.Any())
{
path = request.PathParameters["input"];
}
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = "Hello World. Here are is your path param: " + path,
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } }
};
return response;
}
和list_route
来扩展传统的viewSet。使用此装饰器,您可以添加ViewSet生成的新URL。在这种情况下,list_route
更合适:
detail_route
这将为viewSet添加额外的网址:from rest_framework.decorators import list_route
class BookViewSet(viewsets.ModelViewSet):
...
@list_route()
def new_arrivals(self, request):
books = self.get_queryset()
d=timezone.now()-timedelta(days=14)
books = books.filter(when_added__gte=d
serializer = self.get_serializer(books, many=True)
return Response(serializer.data)
。
答案 1 :(得分:0)
list_route
和detail_route
已贬值,并与装饰器动作合并。
https://www.django-rest-framework.org/community/3.8-announcement/#deprecations