创建一个Django项目,名字:untitled1
创建三张表

from django.db import models


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 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 Book(models.Model):
    title = models.CharField(max_length=32)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish = models.ForeignKey(to="Publish", to_field="nid", related_name='books', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to="Author")

    def __str__(self):
        return self.title

#####################################################################################
# 一对多反向查询
# urls.py
from django.urls import path
from bms import views

urlpatterns = [
    # 一对多反向查询
    path('index', views.PublishView.as_view()),
]

# views.py
class PublishView(APIView):
    def get(self, request):
        publishes = Publish.objects.all()
        serializer_data = PublishSerializer1(publishes, many=True)
        return Response(serializer_data.data)

# publish_serializer.py
class PublishSerializer1(serializers.ModelSerializer):
    book_list = serializers.SerializerMethodField()

    def get_book_list(self, obj):
        # obj是序列化模型的对象
        # 这是Book类,所以这里obj就是图书对象
        print('----->', obj)
		
        books = []
        for book in obj.books.all():
            books.append(book.title)

        return books

    class Meta:
        model = Publish
        fields = ('nid', 'name', 'city', 'email', 'book_list')
#####################################################################################		
# 一对多正向查询/多对多正向查询
# urls.py
from django.urls import path
from bms import views

urlpatterns = [
    # 一对多反向查询
    path('index2', views.PublishView.as_view()),
]

# views.py
class BookView(APIView):
    def get(self, request):
        books = Book.objects.all()
        serializer_data = BookSerializer1(books, many=True)
        return Response(serializer_data.data)

# book_serializer.py
from rest_framework import serializers
from bms.models import Book, Publish


class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = ('nid', 'name', 'city', 'email')


class BookSerializer1(serializers.ModelSerializer):
    # 一对多正向查询
    publish = PublishSerializer()
    # 多对多正向查询
    author_list = serializers.SerializerMethodField()

    # 请注意,get_必须与字段名称一致,否则会报错。
    def get_author_list(self, obj):
        # obj是序列化模型类的对象
        # 这里是Book类,所以obj就是图书对象
        print('----->', obj)
        authors = []
        for author in obj.authors.all():
            authors.append(author.name)

        return authors

    class Meta:
        model = Book
        fields = ('title', 'publishDate', 'price', 'publish', 'author_list')
#####################################################################################	
# urls.py
from django.urls import path
from bms import views

urlpatterns = [
    # 一对多反向查询
    path('index0', views.PublishView.as_view()),
]

# views.py
class BookView2(APIView):
    def get(self, request):
        books = Book.objects.all()
        serializer_data = BookSerializer2(books, many=True)
        return Response(serializer_data.data)
		
# book_serializer.py
class BookSerializer2(serializers.Serializer):
    title = serializers.CharField(max_length=128)
    publishDate = serializers.DateField()
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    # 处理一对多字段
    publish = serializers.CharField()
    publish_title = serializers.CharField(max_length=32, read_only=True, source='publish.name')
    publish_email = serializers.CharField(max_length=32, read_only=True, source='publish.email')
    # 处理多对多字段
    author_list = serializers.SerializerMethodField()

    def get_author_list(self, obj):
        # obj是序列化模型的对象
        # 这是Book类,所以这里obj就是图书对象
        print('----->', obj)
        authors = []
        for author in obj.authors.all():
            authors.append(author.name)

        return authors

#####################################################################################	
# urls.py
from django.urls import path
from bms import views

urlpatterns = [
    # 一对多反向查询
    path('authors', views.AuthorView1.as_view()),
]

# views.py
class AuthorView1(APIView):
    def get(self, request):
        authors = Author.objects.all()
        serializer_data = AuthorSerializer(authors, many=True)
        return Response(serializer_data.data)
		
# author_serializer.py
from rest_framework import serializers
from bms.models import Author


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'