python序列化

Posted veiyg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python序列化相关的知识,希望对你有一定的参考价值。

import json
json.JSONEncoder
点进去 python原生支持的序列化类型
class JSONEncoder(object):
    +-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
"""

Django


# 方式一:

# url(r‘^course/$‘, course.CourseView.as_view()),
# url(r‘^course/(?P<pk>d+)/$‘, course.CourseView.as_view()),


# class CourseView(APIView):
#
# def get(self,request,*args,**kwargs):
#
# ret = {‘code‘:1000,‘data‘:None}
#
# try:
# pk = kwargs.get(‘pk‘)
# if pk:
# obj = models.Course.objects.filter(id=pk).first()
# ser = CourseSerializer(instance=obj,many=False)
# else:
# queryset = models.Course.objects.all()
# ser = CourseSerializer(instance=queryset,many=True)
# ret[‘data‘] = ser.data
# except Exception as e:
# ret[‘code‘] = 1001
# ret[‘error‘] = ‘获取课程失败‘
#
# return Response(ret)
# 方式二 带参数 pk的详情
"""
class ViewSetMixin(object):支持的as_view
view = MyViewSet.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘})
"""

url(r‘^course/$‘, course.CourseView.as_view({‘get‘:‘list‘})),
url(r‘^course/(?P<pk>d+)$‘, course.CourseView.as_view({‘get‘:‘retrieve‘})),

from rest_framework.views import APIView
from rest_framework.response import Response
from api import models
from rest_framework.viewsets import GenericViewSet,ViewSetMixin
from api.serializers.course import CourseSerializer,CourseDetailSerializer


class CourseView(ViewSetMixin,APIView):

def list(self,request,*args,**kwargs):
"""
课程列表接口
:param request:
:param args:
:param kwargs:
:return:
"""
ret = {‘code‘:1000,‘data‘:None}

try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset,many=True)
ret[‘data‘] = ser.data
except Exception as e:
ret[‘code‘] = 1001
ret[‘error‘] = ‘获取课程失败‘

return Response(ret)

def retrieve(self,request,*args,**kwargs):
"""
课程详细接口
:param request:
:param args:
:param kwargs:
:return:
"""
ret = {‘code‘: 1000, ‘data‘: None}

try:
# 课程ID=2
pk = kwargs.get(‘pk‘)

# 课程详细对象
obj = models.CourseDetail.objects.filter(course_id=pk).first()

ser = CourseDetailSerializer(instance=obj,many=False)

ret[‘data‘] = ser.data

except Exception as e:
ret[‘code‘] = 1001
ret[‘error‘] = ‘获取课程失败‘

return Response(ret)




serializers/course.py
from api import models

from rest_framework import serializers
class CourseSerializer(serializers.ModelSerializer):
"""
课程序列化
"""
level = serializers.CharField(source=‘get_level_display‘)
class Meta:
model = models.Course
fields = [‘id‘,‘title‘,‘course_img‘,‘level‘]


class CourseDetailSerializer(serializers.ModelSerializer):
"""
课程详细序列化
"""
# one2one/fk/choice
title = serializers.CharField(source=‘course.title‘)
img = serializers.CharField(source=‘course.course_img‘)
level = serializers.CharField(source=‘course.get_level_display‘)


# m2m
recommends = serializers.SerializerMethodField()
chapter = serializers.SerializerMethodField()


class Meta:
model = models.CourseDetail
fields = [‘course‘,‘title‘,‘img‘,‘level‘,‘slogon‘,‘why‘,‘recommends‘,‘chapter‘]


def get_recommends(self,obj):
# 获取推荐的所有课程
queryset = obj.recommend_courses.all()

return [{‘id‘:row.id,‘title‘:row.title} for row in queryset]

def get_chapter(self,obj):
# 获取推荐的所有课程
queryset = obj.course.chapter_set.all()

return [{‘id‘:row.id,‘name‘:row.name} for row in queryset]












































以上是关于python序列化的主要内容,如果未能解决你的问题,请参考以下文章

python序列化与反序列

Python Json序列化与反序列化

Python之序列化和反序列化

python-序列化

python 序列化

python序列化