获取所有图书的代码实现

books目录下的views.py的python实现代码如下:

from django.views import View
from books.models import BookInfo
from django.http import JsonResponse


class BooksView(View):
    """
    获取所有的数据和保存操作
    """

    def get(self, request):
        # 1, 查询所有图书对象
        books = BookInfo.objects.all()
        # 2, 返回所有图书数据[{},{},......{}]
        book_list = []
        for book in books:
            book_list.append({
                'id': book.id,
                'btitle': book.btitle,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'bpub_date': book.bpub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        pass


class BookView(View):
    """
    获取单一数据、更新和删除
    """

    def get(self, request, pk):
        pass

    def put(self, request, pk):
        pass

    def delete(self, request, pk):
        pass

注意事项:

如果返回的是数组,需要带上 safe=False 参数,否则会报错。

return JsonResponse(book_list, safe=False)

报错信息如下:

'In order to allow non-dict objects to be serialized set the '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.

配置bookmanager目录下的 urls.py 代码如下:

from django.conf.urls import url, include

urlpatterns = [
    url(r'^', include('books.urls')),
]

配置books目录下的 urls.py 代码如下:

from django.conf.urls import url

from . import views

urlpatterns = [
    # 配置查询所有数据的和新增数据的路由
    url(r'^books/$', views.BooksView.as_view()),
    # 配置查询单一数据,修改,删除,需要正则表达式的路由
    url(r'^books/(?P<pk>\d+)/$', views.BookView.as_view())
]