先上models.py文件内容
from django.db import models # 作者表 class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name # 出版社 class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name # 图书列表 class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=15, decimal_places=2) # 外键字段 publish = models.ForeignKey(to="Publish", related_name="book", related_query_name="book_query", on_delete=models.CASCADE) # 多对多字段 authors = models.ManyToManyField(to="Author")
urls.py文件
from django.urls import re_path from xfzapp import views from xfzapp import views2 urlpatterns = [ # 第一步 设置url re_path(r'books/$', views.BookView.as_view()), re_path(r'books/(?P<nid>\d+)/$', views.BookFilterView.as_view()), ]
views.py视图文件
# python内置 import json from django.shortcuts import render, HttpResponse from rest_framework.response import Response from rest_framework.views import APIView from .models import Course, Book, Author, Publish from .xfz_serializers import BookSerializer class BookView(APIView): def get(self, request): # 获取queryset,<QuerySet [<Book: Book object (1)>, <Book: Book object (2)>, ... ]> origin_data = Book.objects.all() # 开始序列化 serialized_data = BookSerializer(origin_data, many=True) # 将序列化后的数据, 响应给客户端 return Response(serialized_data.data) def post(self, request): # 序列化验证,需要导入自定义的序列化类BookSerializer verified_data = BookSerializer(data=request.data) # 验证通过 if verified_data.is_valid(): book = verified_data.save() # 传参的时候要传作者id,不要传作者名字 authors = Author.objects.filter(nid__in=request.data['authors']) # 给书添加作者信息 book.authors.add(*authors) return Response(verified_data.data) # 验证不通过 else: return Response(verified_data.errors) class BookFilterView(APIView): # 继承APIView是因为所有的都是基于它 def get(self, request, nid): book_obj = Book.objects.get(pk=nid) serialized_data = BookSerializer(book_obj, many=False) return Response(serialized_data.data) def delete(self, request, nid): book_obj = Book.objects.get(pk=nid).delete() return Response(book_obj) def put(self, request, nid): book_obj = Book.objects.get(pk=nid) verified_data = BookSerializer(data=request.data, instance=book_obj) if verified_data.is_valid(): verified_data.save() return Response(verified_data.data) else: return Response(verified_data.errors)
序列化文件xfz_serializers.py
# 导入模块 from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'price', 'publish', 'authors', 'publish_name', 'publish_city' ) extra_kwargs = { 'publish_id': {'write_only': True}, 'authors_id': {'write_only': True} } publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name') publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city') authors = serializers.SerializerMethodField() # "get_"是固定格式,"get_"后面部分与author_list保持一致,不能随便写 def get_authors(self, book_obj): # 拿到queryset开始循环 [{}, {}, {}, {}] author_list = list() for author in book_obj.authors.all(): author_list.append(author.name) return author_list
相关文章:
基础班GET/POST接口设计:(Django原生序列化)
https://www.cnblogs.com/apollo1616/articles/10084614.html
进阶版GET/POST接口设计:
https://www.cnblogs.com/apollo1616/articles/10085132.html