Django-rest 시리얼화(사용자 정의serializers)

5171 단어 Django
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출처: 약서 저작권은 작가에게 귀속된다.상업 전재는 작가에게 연락하여 권한을 부여받고, 비상업 전재는 출처를 밝혀 주십시오.

좋은 웹페이지 즐겨찾기