这个东西上一篇写过了......

这一片改进的地方主要是在序列化类,所以代码放在最前面了

上一篇文章地址:

https://www.cnblogs.com/apollo1616/articles/10084614.html

序列化文件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', 'author_list', 'publish_name', 'publish_city' ) extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'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') author_list = serializers.SerializerMethodField() # "get_"是固定格式,"get_"后面部分与author_list保持一致,不能随便写 def get_author_list(self, book_obj): # 拿到queryset开始循环 [{}, {}, {}, {}] authors = list() for author in book_obj.authors.all(): authors.append(author.name) return authors

 

视图文件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)

 

数据库文件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")