How to obtain the data table B when Django Rest framework sequences of Table A

The following model

from django.db import models


# Create your models here.


class Author(models.Model):
    """
    Book authors table
    """
    name = models.CharField('作者姓名', max_length=20)
    age = models.SmallIntegerField('年龄')

    def __str__(self):
        return self.name


class Book(models.Model):
    """
    Book Table
    "" " 
    BOOK_NAME = models.CharField ( ' Book Title ' , MAX_LENGTH = 100 )
    author = models.ForeignKey(Author, related_name='author_book')
    publish_time = models.DateTimeField ( ' Published ' , auto_now_add = True)

    def __str__(self):
        return self.book_name

Book a table in which the author is a foreign key field, representing a plurality of corresponding to a book author (in fact, the reality may be a corresponding number of books, which is many relationships, here reduced to a foreign key)

View class as follows:

from rest_framework import generics, serializers
from ..models import Author


class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Author
        fields = '__all__'



class AuthorList(generics.ListAPIView):
    """
    All inquiries author information, and books written correspondence
    """
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

The above model only Author serialized, the output interface information:

 

 We assume that there is a demand now is: return all the books corresponding author.

analysis:

  Realization of the above sequence Author information reading only a model, so that the interface itself is only returned table field, the need to return the corresponding book information table will need to take data from the book across the model.

Author serializer transformation is as follows:

class AuthorSerializer(serializers.ModelSerializer):
    # 该字段信息通过下方的get_books方法获取数据
    books = serializers.SerializerMethodField()

    class Meta:
        model = Author
        fields = '__all__'

    # 方法名称必须与上面定义的序列化字段一致,格式为:"get_自定义字段名"
    def get_books(self, author_obj):
        # 通过book模型中的author字段的related_name反查出作者对应的图书集合
        book_query_set = author_obj.author_book.all()
        # 遍历图书集合获取图书的名称和出版时间,并返回
        return {'count': book_query_set.count(),
                "data": [{'name': book_obj.book_name, 'publish_time': book_obj.publish_time} for
                         book_obj in book_query_set]}

此时接口返回信息为:

 

满足要求,实现 

 

Guess you like

Origin www.cnblogs.com/gcgc/p/12101571.html