1. 安装
pip install djangoframework
2. app注册 rest_framework
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app.apps.AppConfig',
'rest_framework'
]
3. 自定义序列化程序,创建一个serializers序列器
serializer.CharField(source='orm操作')
from rest_framework import serializers class PublisherS(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32) class AuthorS(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=32) class BookS(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)
pub_time = serializers.DateField()
category = serializers.IntegerField(source='get_category_display') publisher = PublisherS()
authors = AuthorS(many=True)
4. views 中导入
from rest_framework.views import APIView
from rest_framework.response import Response
from app.models import Book
from .serializer import BookS class BookView(APIView):
def get(self,request):
book_queryset = Book.objects.all()
#用序列器序列化出一个对象
ser_obj = BookS(book_queryset,many=True)
return Response(ser_obj.data) def post(self,request):
...