^_^
# [{title,price},{}] 构造的数据结构 简单的FBV/CBV def showbooks(request): # FBV if request.method =='GET': books_list = models.Book.objects.all() l1 =[] # 列表 for book_obj in books_list: d1 = {} d1['title'] = book_obj.title d1['price'] = book_obj.price l1.append(d1) return HttpResponse(json.dumps(l1,ensure_ascii=False)) #结局中文编码 class BookHandle(View): # CBV #url - view -- 自己创建的类中dispatch (View dispatch) 反射找到对应请求方式的方法 def dispatch(self, request, *args, **kwargs): res = super().dispatch(request, *args, **kwargs) return res def get(self,request): books_list = models.Book.objects.all() l1 =[] for book_obj in books_list: d1 = {} d1['title'] = book_obj.title d1['price'] = book_obj.price l1.append(d1) # return HttpResponse(json.dumps(l1,ensure_ascii=False)) return render(request,'login.html') def post(self,request): print(request.POST) return HttpResponse('ok')
# 一个 django 提供的序列化组件
from django.shortcuts import render,HttpResponse,redirect
import json
from django.views import View
from app01 import models
from rest_framework import APIView from django.core.serializers import serialize from rest_framework.response import Response class BookHandle(APIView): def get(self,request): books_list = models.Book.objects.all() cs = serialize('json',books_list,ensure_ascii=False) #解决中文问题 return Response(cs)
# json 序列化时间日期格式的时候的方法
import json from datetime import datetime from datetime import date #对含有日期格式数据的json数据进行转换 class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field,datetime): return field.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field,date): return field.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self,field) d1 = datetime.now() dd = json.dumps(d1,cls=JsonCustomEncoder) print(dd)
# drf 序列化组件
from django.shortcuts import render,HttpResponse,redirect
import json
from django.views import View
from app01 import models
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
#from rest_framework import status #返回指定状态码的时候会用到
#return Response(se_data,status=status.HTTP_400_BAD_REQUEST)
#或者这种方式返回来指定状态码:return JsonResponse(serializer.data, status=201)
class BookSerializer(serializers.Serializer): # 类 models.Model
title = serializers.CharField(max_length=22) # 必要字段的话required = False
price = serializers.IntegerField()
class BookHandle(APIView):
def get(self,request):
books_list = models.Book.objects.all()
cs = BookSerializer(books_list,many=True)
print(cs.data) # QuerySet 对象 要用many=Ture
return Response(cs.data)
def post(self, request):
print(request.data)
cs = BookSerializer(data=request.data,many=False) #dict 类型
print(cs.is_valid()) # 布尔值
if cs.is_valid():
models.Book.objects.create(**cs.data)
return HttpResponse(cs.data)
else:
print(cs.errors)
return Response(cs.errors)
一套简易流程 -- drf 以及接口规范
首先按照restful规范咱们创建一些api接口,按照下面这些形式写吧: Courses --- GET ---> 查看数据----->返回所有数据列表[{},{},] Courses--- POST --->添加数据 -----> 返回添加的数据{ } courses/1 ---PUT---> 更新pk=1的数据 ----->返回更新后的数据{ } courses/1 --- DELETE---> 删除pk=1的数据 -----> 返回空 courses/1 --- GET --->查看单条数据 -----> 返回单条数据 { }
我们先看一个drf给我们提供的一个类似于Postman功能的页面,首先我们创建一个django项目,创建一个Course表,然后添加一些数据
一 引入drf 的Response对象 from django.shortcuts import render,HttpResponse,redirect import json from django.views import View from app01 import models from rest_framework.views import APIView from rest_framework.response import Response # CBV视图 class CourseView(APIView): def get(self,request): course_obj_list = models.Course.objects.all() ret = [] for course_obj in course_obj_list: ret.append({ "title":course_obj.title, "desc":course_obj.desc, }) return Response(json.dumps(ret, ensure_ascii=False)) #这里使用Response来返回消息 def post(self,request): print(request.data) return HttpResponse('POST')
二 在settings.py 里面注册 APP
INSTALLED_APPS = ['rest_framework', #将它注册成App]
三 配置路由
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^courses/', views.CourseView.as_view(),name='courses'), ]
四 启动项目,浏览器访问路由,在这里面可以发送不同的请求,看到对应的相应数据,类似于postman,建议使用postman
表查询 一对一与一对多的区别 一对一就是一对多张外键加unique