1.修改路由配置 Urls.py
from django.contrib import admin
from django.urls import path, re_path
from .views1 import user_list, user_single
# 支持URL添加后缀
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('users/', user_list),
re_path(r'users/(.+?)/', user_single),
]
# 支持URL添加后缀
urlpatterns = format_suffix_patterns(urlpatterns)
- 实现增删改查
# api_view定义接口视图的
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from django.http import JsonResponse, HttpResponse
from .models import UserInfoModel, RelevanceModel
from .serializers1 import UserInfoSerializers, RelevanceSerializers
from rest_framework.views import APIView
class UserListView(APIView):
def get(self, request, format=None):
# 获取模型类所有数据
users = UserInfoModel.objects.all()
# 创建序列化器对象
ser = UserInfoSerializers(users, many=True)
return Response(data={"code": 200, "message": "OK", "data": ser.data}, status=status.HTTP_200_OK)
def post(self, request, format=None):
# 创建序列化器
ser = UserInfoSerializers(data=request.data)
# 校验数据
if ser.is_valid():
# 保存数据
ser.save()
return Response({'code': 201, 'message': 'OK', 'data': ser.data}, status=status.HTTP_201_CREATED)
else:
return Response({'code': 400, 'message': '添加失败', 'data': ser.data}, status=status.HTTP_400_BAD_REQUEST)
class UserSingleView(APIView):
def get(self, request, id, format=None):
# 数据不正确抛出异常
try:
users = UserInfoModel.objects.get(id=id)
except Exception as e:
return Response({"code": 404, "message": "数据不存在"}, status=status.HTTP_404_NOT_FOUND)
# 创建序列化器对象
ser = UserInfoSerializers(users)
return Response({"code": 200, "message": "OK", "data": ser.data}, status=status.HTTP_200_OK)
def put(self, request, id, format=None):
# 数据不正确抛出异常
try:
users = UserInfoModel.objects.get(id=id)
except Exception as e:
return Response({"code": 404, "message": "数据不存在"}, status=status.HTTP_404_NOT_FOUND)
# 创建序列化器
ser = UserInfoSerializers(instance=users, data=request.data)
# 校验数据
if ser.is_valid():
# 保存数据
ser.save()
return Response({'code': 200, 'message': 'OK', 'data': ser.data}, status=status.HTTP_200_OK)
else:
return Response({'code': 400, 'message': ser.errors}, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, id, format=None):
# 数据不正确抛出异常
try:
users = UserInfoModel.objects.get(id=id)
except Exception as e:
return Response({"code": 404, "message": "数据不存在"}, status=status.HTTP_404_NOT_FOUND)
users.delete()
return Response(status=status.HTTP_204_NO_CONTENT)