$Django 序列化组件

1 序列化组件

from app01 import models
from rest_framework import serializers
from rest_framework.serializers import  Serializer,ModelSerializer
from django.http import JsonResponse

class auth(Serializer):
    name=serializers.CharField()
    age=serializers.CharField()
#方式1
class ser(Serializer): #*****如果不指定source,字段必须对应起来,如果指定了source,字段可以任意命名
    a=serializers.CharField(source=‘name‘) #source 可以指定字段,也可也指定方法
    b=serializers.CharField(source=‘authors‘)
    c=serializers.CharField(source=‘publish.name‘)
    d=serializers.CharField(source=‘publish.test‘)
    e=serializers.SerializerMethodField()
    # 方法名:叫get_字段名,要传参数,参数是:当前book对象
    def get_e(self,obj): #obj为book对象
        # for循环
        # li=[{‘name‘:i.name,‘age‘:i.age} for i in obj.authors.all()]
        # return li
        #序列化
        auths=obj.authors.all()
        li=auth(auths,many=True)
        return li.data
#方式2
class ser1(ModelSerializer):
    class Meta:
        model=models.Book
        fields=‘__all__‘
        # fields=[‘name‘,‘price‘]
        # exclude=[‘authors‘]
        depth=10 #深度为1 当前模型字段 为2跨1个表的字段
#cbv视图
class show(APIView):
    def get(self,request):
        #drf
        books=models.Book.objects.all()
        bb=ser1(instance=books,many=True)  #queryset对象/也可以是多单个对象|||many指定单个多个
        print(bb.data) #json格式dic
        return JsonResponse(bb.data,safe=False)
        #django自带的
        # from django.core import serializers
        # books=models.Book.objects.all()
        # ret=serializers.serialize(‘json‘,books)
        # print(ret,type(ret)) #json格式str
        # dic = {‘data‘: ret}
        # return HttpResponse(ret)

Serializer与ModelSerializer

原文地址:https://www.cnblogs.com/3sss-ss-s/p/10102928.html

时间: 2024-11-06 07:09:22