在Django REST Framework中,可以通过以下步骤将查询集作为JSON响应返回:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
return Response(serializer.data)
from django.urls import path
from .views import BookViewSet
urlpatterns = [
path('books/', BookViewSet.as_view({'get': 'list'}), name='book-list'),
]
现在,当访问'books/'路径时,Django REST Framework将会返回查询集的JSON响应。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)、腾讯云对象存储(COS)、腾讯云数据库MySQL版(TencentDB for MySQL)等。你可以在腾讯云官网上找到这些产品的详细介绍和文档链接。
领取专属 10元无门槛券
手把手带您无忧上云