保存图书的代码实现

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

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


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):
        # 1获取前端数据
        data = request.body.decode()  # 得到一个json的字符串
        data_dict = json.loads(data)  # 转换成字典形式
        # 2验证数据
        btitle = data_dict.get('btitle')  # 尽量使用get,如果没有接受到数据它不会产生异常,会返回None
        # btitle = data_dict['btitle']  # 如果没有接受到数据会产生异常
        bpub_date = data_dict.get('bpub_date')
        if btitle is None or bpub_date is None:
            return JsonResponse({"error": "错误信息"}, status=400)
        # 3保存数据
        book = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        # 4返回结果
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'bpub_date': book.bpub_date
        })


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

    def get(self, request, pk):
        pass

    def put(self, request, pk):
        pass

    def delete(self, request, pk):
        pass