闲话不聊....

直接上数据库模型代码models.py内容

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=5, 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


urlpatterns = [
    re_path(r'books/$', views.BookView.as_view()),
]

在接下来就是视图函数views.py文件

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)

序列化类所在文件,也是一个py文件,自己命名

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 导入模块
from rest_framework import serializers


# 创建一个序列化类,字段类型不一定要跟models的字段一致
class BookSerializer(serializers.Serializer):
    # nid是自增字段,所以不需要这里添加
    # nid = serializers.CharField(max_length=32)
    title = serializers.CharField(max_length=128)
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    publish = serializers.CharField()
    # 外键字段, 显示__str__方法的返回值
    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")

    # 多对多字段需要自己手动获取数据,SerializerMethodField()
    authors = serializers.SerializerMethodField()
    # 'get_'固定格式,后面要与上面变量一直,这里指的是authors
    def get_authors(self, book_obj):
        author_list = list()

        for author in book_obj.authors.all():
            author_list.append(author.name)

        return author_list

    def create(self, validated_data):
        from .models import Book
        # validated_data处理前:
        # {'title': '坏蛋是怎么连城的', 'price': Decimal('188.00'), 'publish': '1'}

        # 下面这句作用把publish转成publish_id
        validated_data['publish_id'] = validated_data.pop('publish')

        # validated_data处理后:
        # {'title': '坏蛋是怎么连城的', 'price': Decimal('188.00'), 'publish_id': '1'}
        book = Book.objects.create(**validated_data)
        return book

 

文章最后给大家介绍一个工具POSTMAN,通过这个模仿浏览器发请求.get请求可能无所谓,重点是发post传参时候,用这个比较方便

针对上面的代码我执行下

首先我上一张get请求的图,get请求就是增删改查中的查

 

最后发一张post请求的图,也就是我们说的添加

 

 

接下来在去数据库看看有没有添加成功