安装:pip install djangorestframework
在使用drf之前,先
使用原生Django实现5个接口
python
from django.db import models
class Book(models.Model):
name=models.CharField(max_length=53)
price=models.IntegerField()
python
from app01 import models
from django.http import JsonResponse
import json
from django.views import View
class BookView(View):
def get(self,request):
book_list=models.Book.objects.all()
l=[]
for book in book_list:
l.append({'name':book.name,'price':book.price})
return JsonResponse({'code':100,'msg':'ok','results':l})
def post(self,request):
data=json.loads(request.body)
book=models.Book.objects.create(**data)
return JsonResponse({'code':100,'msg':'ok','results':{'name':book.name,'price':book.price}})
class BookDetailView(View):
def get(self,request,pk):
book=models.Book.objects.filter(pk=pk).first()
return JsonResponse({'code':100,'msg':'ok','results':{'name':book.name,'price':book.price}})
def delete(self,request,pk):
models.Book.objects.filter(pk=pk).delete()
return JsonResponse({'code':100,'msg':'ok'})
def put(self,request,pk):
data=json.loads(request.body)
print(data)
book=models.Book.objects.filter(pk=pk).first()
book.name=data.get('name')
book.price=data.get('price')
book.save()
return JsonResponse({'code':100,'msg':'ok','result':{'name':book.name,'price':book.price}})
python
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()),
]
以上是Django实现的5个接口,在用drf实现5个接口之前,先介绍下序列化类
序列化类介绍
在前后端分离开发中,对于RESTfulAPI设置,我们一般需要将查询/更新数据以JSON方式进行返回,而Django本身所带的ORM,仅仅支持数据的查询,并不能将查询得到的数据转换为JSON/Python的字典易读格式,而DRF为我们提供了方便的序列化器自定义类,可以通过定义序列化类,方便的返回我们所需要的数据。
序列化类可以做什么?
序列化:ORM查询结果/对象 ---> 转换为Python原生数据类型/其他可读类型(如字典或列表)---> 便于转换JSON/其他传输格式
反序列化:请求数据(通常为JSON) -> Python可读取数据结构,对象/字典,校验数据是否合法,
前端传入数据,存到数据库中。
序列化类的使用
DRF的序列化器,位于以下位置
from rest_framework import serializers
使用步骤:
1.写个py文件,叫serializer.py
2.写个类,继承serializers.Serializer
3.在类中写要序列化的字段
class PublishSerializer(serializers.Serializer):
写字段,要序列化的字段
name = serializers.CharField()
addr = serializers.CharField()
id = serializers.IntegerField()
4.在视图类中使用,完成 序列化
-多条
-ser = PublishSerializer(instance=publish_list, many=True)
-ser.data 序列化后的数据
-单条:
-ser = PublishSerializer(instance=publish)
-ser.data 序列化后的数据
使用drf实现5个接口
python
from django.db import models
class Books(models.Model):
name=models.CharField(max_length=43)
price=models.IntegerField()
python
from rest_framework import serializers
from app01 import models
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Books
fields = '__all__'
python
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.viewsets import ModelViewSet
class BookView(ModelViewSet):
queryset = models.Books.objects.all()
serializer_class = BookSerializer
python
from app01 import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('books', views.BookView, 'books')
urlpatterns = [
]
urlpatterns += router.urls