1. 程式人生 > >序列化組件

序列化組件

簡單的 pre queryset 課程 ret turn comm end get

序列化組件

  • 使用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‘)

序列化組件