目录
用各种思路实现五个接口的编写
那么是哪五个接口呢?查询所有、查询单个、新增数据、修改数据、删除数据
各个方法其实用的都是同样的表数据所以干脆提前准备好 再说了代码也没那么复杂
# 1.创建Django项目随手修改配置文件
# 2.在models.py里面写表数据,代码如下
from django.db import models
class Book(models.Model):
"""书籍表"""
name = models.CharField(max_length=32)
price = models.CharField(max_length=32)
publish = models.CharField(max_length=32)
# 3.进行数据库迁移
数据库就不用MySQL,因为结构简单就用sqlite而且是本地测试 因此不用改数据库配置
makemigrations
migrate
# 4.录入伪数据
双击数据库小图标就可以进去录入数据或用Navicat也可以的
一、基于Django原生写五个接口
1.视图层代码
from django.http import JsonResponse
from .models import Book
from django.views import View
import json
class BookView(View):
"""1.查所有数据"""
def get(self, request):
# 查询出所有图书,queryset对象,不能直接给前端
books = Book.objects.all()
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})
"""2.新增一条数据"""
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):
"""3.查询单个数据"""
def get(self, request, pk):
book = Book.objects.filter(pk=pk).first()
return JsonResponse({'id': book.id, 'name': book.name, 'price': book.price, 'publish': book.publish})
"""4.修改数据"""
def put(self, request, pk):
# 查到要改的
book = Book.objects.filter(pk=pk).first()
# 前端使用json格式提交 自己保存
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({'id': book.id, 'name': book.name, 'price': book.price, 'publish': book.publish})
def delete(self, request, pk):
"""5.删除数据"""
Book.objects.filter(pk=pk).delete()
return JsonResponse(data={})
2.路由层代码
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/books/<int:pk>/',views.BookDetailView.as_view()),
path('api/v1/books/', views.BookView.as_view()),
]
二、基于drf实现五个接口的编写
1.视图层代码
from .serializer import BookSerializer
from rest_framework.viewsets import ModelViewSet
class BookView(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
2.序列化代码
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
3.路由层代码
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('books', views.BookView, 'books')
urlpatterns = [
path('admin/', admin.site.urls),
]
# 两个列表相加 [1,2,4] + [6,7,8]=
urlpatterns += router.urls
三、基于序列化器编写五个接口
1.路由层代码
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', views.BookView.as_view()),
path('books/<int:pk>/', views.BookDetailView.as_view()),
]
2.视图层代码
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializer import BookSerializer
class BookView(APIView):
"""1.查所有数据 序列化过程"""
def get(self, request):
books = Book.objects.all()
# 需要序列化类来完成---得有序列化类即BookSerializer
# instance参数是要序列化的数据books queryset对象
# 要传的数据是多条那就得加上many=True参数,如果是单挑就不用传
ser = BookSerializer(instance=books, many=True)
return Response(ser.data)
def post(self, request):
"""2.新增数据 反序列化过程"""
# request.data 前端提交数据---校验数据---存数据,前端传入的数据给data参数
ser = BookSerializer(data=request.data)
# 校验数据
if ser.is_valid():
ser.save()
return Response({'code':100, 'msg':'新增成功', 'result':ser.data})
else:
return Response({'code':101, 'msg':ser.errors})
class BookDetailView(APIView):
"""3.获取单个数据 序列化过程"""
def get(self, request, *args, **kwargs):
book = Book.objects.filter(pk=kwargs.get('pk')).first()
ser = BookSerializer(instance=book)
return Response(ser.data)
def put(self, requet, pk):
"""4.修改数据 反序列化过程"""
book = Book.objects.filter(pk=pk).first()
ser = BookSerializer(data=requet.data, instance=book)
if ser.is_valid():
ser.save()
return Response({'code':100, 'msg':'修改数据', 'result':ser.data})
else:
return Response({'code':101, 'msg':ser.errors})
def delete(self, request, pk):
Book.objects.filter(pk=pk).delete()
return Response({'code':100,'msg':'删除成功'})
3.序列化代码
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import Book
class BookSerializer(serializers.Serializer):
# 序列化模型表的三个字段
name = serializers.CharField()
price = serializers.CharField()
publish = serializers.CharField()
def create(self, validated_data):
"""数据保存逻辑"""
# 保存到数据库
# validated_data是校验过后的数据
book = Book.objects.create(**validated_data)
return book
def update(self, instance, validated_data):
"""数据更新逻辑"""
# instance是要修改的对象
instance.name = validated_data.get('name')
instance.price = validated_data.get('price')
instance.publish = validated_data.get('publish')
# orm的单个对象 修改了单个对象的属性 只要调用对象.save就能把修改保存的数据库
instance.save()
# 返回修改后的对象
return instance
def validate_name(self, name):
# 校验name是否合法
if name.startswith('sb'):
# 校验啊不能通过 抛异常
raise ValidationError('名字不能以sb开头')
else:
return name
def validate(self, attrs):
# 校验过后的数据 书名跟出版社名字不能一样
if attrs.get('name') == attrs.get('publish'):
raise ValidationError('书名和出版社名不能一样')
else:
return attrs
标签:name,price,接口,book,publish,import,编写,思路,data
From: https://www.cnblogs.com/almira998/p/17084700.html