5. 父表获取从表所有信息 / 从表获取父表所有信息(自定义序列化器)
定义一个序列化器类,指定要返回的父表字段,然后将这个序列化器类作为子表Serializer中的字段即可;从表同理
子表Serializer中的字段:命名用子表模型中的外键名
父表Serializer中的字段:命名用related_name 或 从表模型类名小写_set
从表中返回父表字段 interfaces/serializers.py from rest_framework import serializers from projects.models import Projects class OneProjectsSerializer(serializers.Serializer): """ 定义一个序列化器类,指定要返回的父表字段 """ id = serializers.IntegerField() name = serializers.CharField() leader = serializers.CharField() is_execute = serializers.BooleanField() desc = serializers.CharField() create_time =serializers.DateTimeField() update_time = serializers.DateTimeField() class InterfacesSerializer(serializers.Serializer): id = serializers.IntegerField(label='id主键', help_text='id主键', required=False) name = serializers.CharField(label='接口名称', help_text='接口名称', max_length=15, error_messages={'max_length': 'name不能超过15字'}) tester = serializers.CharField(label='测试人员', help_text='测试人员', max_length=10, error_messages={'max_length': 'tester不能超过15字'}) create_time = serializers.DateTimeField(label='创建时间', help_text='创建时间', required=False, read_only=True) update_time = serializers.DateTimeField(label='更新时间', help_text='更新时间', required=False, read_only=True) # projects = serializers.StringRelatedField(label='所属项目名称', help_text='所属项目名称') # projects = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(), label='项目id', help_text='项目id') projects = OneProjectsSerializer(label='获取父表projects所有信息',help_text='获取父表projects所有信息',read_only=True) interfaces/models.py from django.db import models class Interfaces(models.Model): id = models.AutoField(primary_key=True, verbose_name='id主键', help_text='id主键') name = models.CharField(verbose_name='接口名称', help_text='接口名称', max_length=15, unique=True) tester = models.CharField(verbose_name='测试人员', help_text='测试人员', max_length=10) create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', help_text='创建时间') update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间', help_text='更新时间') projects = models.ForeignKey('projects.Projects', on_delete=models.CASCADE, related_name='interfaces')