序列化: 第一版: class RolesView(APIView): def get(self,request,*args,**kwargs): roles = models.Role.objects.all().values('id','title') roles = list(roles) #利用json.dumps将数据转换成json格式 ret = json.dumps(roles,ensure_ascii=False) return HttpResponse(ret) 第二版: from rest_framework import serializers class RloesSerializer(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField() class RolesView(APIView): def get(self,request,*args,**kwargs): 方式一:对于[obj,obj,obj,] roles = models.Role.objects.all() ser = RloesSerializer(instance=roles, many=True) #多个对象 方式二:对于[obj,obj,obj,] roles = models.Role.objects.all().first() ser = RloesSerializer(instance=roles, many=False) #单个对象或数据 ret = json.dumps(ser.data,ensure_ascii=False) return HttpResponse(ret) 第三版: from rest_framework import serializers class UserInfoSerializer(serializers.Serializer): # source是印射models里面的表的字段名 user_type = serializers.CharField(source='user_type') # 如果字段时choices字段 可以使用source='get_字段名_display' 来显示中文 user_type_zhongwen = serializers.CharField(source='get_user_type_display') username = serializers.CharField() password = serializers.CharField() #如果字段是一个Forenighkey那么可以使用 字段名加点来关联其他表的字段 gpid = serializers.CharField(source='group.id') #如果字段是一个ManyToMany那么可以使用 字段名加点来关联所有字段 rls = serializers.CharField(source='roles.all') #自定义显示 rls = serializers.SerializerMethodField() #自定义方法 def get_rls(self,row): role_obj_list = row.roles.all() ret = [] for item in role_obj_list: ret.append({'id':item.id,'title':item.title}) return ret class UserInfoView(APIView): def get(self,request,*args,**kwargs): roles = models.UserInfo.objects.all() ser = UserInfoSerializer(instance=roles, many=True) #多个对象 ret = json.dumps(ser.data,ensure_ascii=False) return HttpResponse(ret)
第四版: from rest_framework import serializers class UserInfoSerializer(serializers.ModelSerializer):
#反向生成url 根据路由 url(r^(?P<version>[v1|v2]+)/group/(?P<pk>d+)$, view.UserInfoView.as_view(),'gp')
group = serializers.HyperlinkedIdentityField(view_name='gp',lookup_field='group_id',lookup_url_kwarg='pk') user_type_zhongwen = serializers.CharField(source='get_user_type_display') class Meta: model = models.UserInfo # 显示UserInfo全部字段 fields = "__all__" # 可以自定义字段 fields = ['id','username','password','user_type_zhongwen',]
#默认是0,大于等于1时 就会把字段的相关的Forengishkey或者ManyToMany或者OneToOne
#建议不要超过3 (0-10) depth = 1 class UserInfoView(APIView): def get(self,request,*args,**kwargs): roles = models.UserInfo.objects.all() ser = UserInfoSerializer(instance=roles, many=True) #多个对象 ret = json.dumps(ser.data,ensure_ascii=False) return HttpResponse(ret)
使用第四版
1. 继承 serializers.ModelSerializer
2. class Meta:
model = models.<表名>
fields = "__all__"
3. 可以自定义字段 fields = ['id','username','password','user_type_zhongwen',]
4. depth = 1 #默认是0,大于等于1时 就会把字段的相关的Forengishkey或者ManyToMany或者OneToOne