序列化组件
Posted stupid-dog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化组件相关的知识,希望对你有一定的参考价值。
序列化组件
- 使用depth获取跨表数据
当有表有外键存在时,在序列化组件时简单的获取关联表的数据方法
class CourseSerializers(ModelSerializer):
class Meta:
model = Course
fields = ‘__all__‘
depth = 1 # 建议0-10 当为0时,无作用,当为1时,可以获取外键关联的表的数据,当为2时可获取外键关联的表再关联的表的数据
- 使用source获取OneToOne关联表的数据,获取model中choices中的中文
class CourseDetailSerializer(ModelSerializer):
# 自定义字段实现获取一对一跨表数据
title = serializers.CharField(source=‘course.title‘)
src = serializers.CharField(source=‘course.src‘)
#获取model中choices中的中文
leave = serializers.CharField(source=‘course.get_leave_display‘)
class Meta:
model = Course
fields = [‘title‘,‘src‘,‘leave‘]
- serializers.SerializerMethodField()获取跨表的多条数据
class CourseDetailSerializer(ModelSerializer):
# 自定义字段实现获取一对一跨表数据
title = serializers.CharField(source=‘course.title‘)
src = serializers.CharField(source=‘course.src‘)
#获取model中choices中的中文
leave = serializers.CharField(source=‘course.get_leave_display‘)
recommends = serializers.SerializerMethodField()
chapter = serializers.SerializerMethodField()
def get_chapter(self,obj):
queryset = obj.course.chapter_set.all()
return [{‘num‘:item.num,‘name‘:item.name} for item in queryset]
def get_recommends(self,obj):
queryset = obj.recommend_course.all()
return [{‘id‘:item.id,‘title‘:item.title} for item in queryset]
class Meta:
model = CourseDetail
fields = [‘course‘,‘slogon‘,‘why‘,‘leave‘,‘title‘,‘src‘,‘recommends‘,‘chapter‘]
# models.py
from django.db import models
class Course(models.Model):
‘‘‘课程表‘‘‘
leave_choices = (
(0, ‘初级课程‘),
(1, ‘中级课程‘),
(2, ‘高级课程‘),
)
title = models.CharField(max_length=32, verbose_name=‘课程名称‘)
src = models.CharField(verbose_name=‘课程图片‘, max_length=128)
leave = models.SmallIntegerField(verbose_name=‘课程难易程度‘, choices=leave_choices, default=0)
class CourseDetail(models.Model):
‘‘‘课程详情‘‘‘
course = models.OneToOneField(verbose_name=‘课程名称‘, to=‘Course‘)
slogon = models.CharField(verbose_name=‘口号‘, max_length=64)
why = models.CharField(verbose_name=‘学习目的‘, max_length=255)
recommend_course = models.ManyToManyField(verbose_name=‘推荐课程‘, to=‘Course‘,related_name=‘rc‘)
class Chapter(models.Model):
‘‘‘章节表‘‘‘
num = models.IntegerField(verbose_name=‘章节‘)
name = models.CharField(verbose_name=‘章节名称‘, max_length=32)
course = models.ForeignKey(verbose_name=‘所属课程‘, to=‘Course‘)
以上是关于序列化组件的主要内容,如果未能解决你的问题,请参考以下文章