Django——rest序列化(自定义serializers)

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from repository import models
from rest_framework import serializers

class MyField(serializers.CharField):
    #返回数据到to_respresentation
    def get_attribute(self, instance):
        teacher_list = instance.teachers.all()
        return teacher_list
    #格式化数据
    def to_representation(self, value):
        ret = []
        for row in value:
            ret.append({'id': row.id,'name':row.name})
        return ret


class TestSerializer(serializers.ModelSerializer):
    # get_attribute, 去数据库中获取值
    # to_representation,在页面中显示值
    # level_name = serializers.CharField(source='get_level_display') # obj.get_level_display
    # test_char= serializers.CharField(source='xx.xx.xx') # 以.的形式跨表
    x1 = serializers.SerializerMethodField()
    xx = MyField()
    class Meta:
        model = models.Course
        fields = ['name','level_name']

    def get_x1(self,obj):
        pass

在ModelSerializer直接以get_字段的形式

class CouserDetailSerializer(serializers.ModelSerializer):
    course_name = serializers.CharField(source='course.name')
    recommend_courses_list = serializers.SerializerMethodField()
    price_policy_list = serializers.SerializerMethodField()

    class Meta:
        model = models.CourseDetail
        fields = ['id','course_name','recommend_courses_list']

    def get_recommend_courses_list(self,obj):
        ret = []
        course_list = obj.recommend_courses.all()
        for item in course_list:
            ret.append({'id':item.id,'name':item.name})
        return ret

    def get_price_policy_list(self,obj):
        # 当前课程所有的价格策略
        # ret = []
        # price_policy_list = obj.course.price_policy.all()
        # return ret

        # ret = []
        # price_policy_list = models.PricePolicy.objects.filter(content_type__app_label='repository',
        #                                   content_type__model='course',
        #                                   object_id=obj.couser_id)
        # return ret
        return "ssss"

作者:lkning
链接:https://www.jianshu.com/p/f23fd7a3abe5
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(Django)