Django原生即继承View来实现写接口,的确过程很繁杂,很多东西都是手动写,大致思路就是在视图层实现数据的序列化与反序列化,然后配两个路由,因为查单个数据和查所有用同一个接口会有点麻烦。当然首先写表模型,越简单越好。
1.写模型表以及数据库迁移
# 在models.Py中写如下代码
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=32, verbose_name='书名')
price = models.CharField(max_length=32, verbose_name='价格')
publish = models.CharField(max_length=32, verbose_name='出版社')
本次是因为小型本地测试所以用sqlite数据库即可,迁移完成之后录入一些伪数据,双击目录栏那边的数据库图标可以进入数据库里面,进行录入数据,暂且只需要录入两条数据
3.使用CBV写查询所有的视图接口
from django.shortcuts import render
from django.views import View
from .models import Book
from django.http import JsonResponse
from django.http import HttpResponse
import json
class BookView(View):
def get(self, request): # 查询所有
# 首先查出所有的图书
books = Book.objects.all()
# 转成json格式 进行序列化(最终原始的序列化)
book_list = []
for book in books:
book_list.append({'name': book.name, 'price': book.price, 'publish': book.publish})
return JsonResponse(book_list, safe=False, json_dumps_params={'ensure_ascii': False})
# return HttpResponse(json.dumps(book_list, ensure_ascii=False))
def post(self, request): # 新增一个
# 获取前端传入的数据
name = request.POST.get('name')
price = request.POST.get('price')
publish = request.POST.get('publish')
# 存储到数据库中
book = Book.objects.create(name=name, price=price, publish=publish)
# 返回新增的对象
return JsonResponse({'name': book.name, 'price': book.price, 'publish': book.publish})
class BookDetailView(View):
def get(self, request, pk): # 查询一个
# 首先按照pk筛出来
book = Book.objects.filter(pk=pk).first()
# 然后一定返回该数据
return JsonResponse({'name': book.name, 'price': book.price, 'publish': book.publish})
def put(self,request, pk):
# 也是先查出来
book = Book.objects.filter(pk=pk).first()
# 在修改该数据
book_dict = json.loads(request.body)
book.name = book_dict.get('name')
book.price = book_dict.get('price')
book.publish = book_dict.get('publish')
# 保存修改结果
book.save()
# 返回修改结果
return JsonResponse({'name':book.name, 'price':book.price, 'publish':book.publish})
4.配路由
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/books/', views.BookView.as_view()),
path('api/v1/books/<int:pk>/', views.BookDetailView.as_view()),
]