Django Rest framework 序列化
1 序列化入门
1 2 3 4 | class RoleSerializer(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField() label = serializers.CharField() |
2 进阶序列化1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class UserSerializer(serializers.Serializer): id = serializers.IntegerField() username = serializers.CharField() nick_name = serializers.CharField() password = serializers.CharField() state = serializers.BooleanField() is_super = serializers.BooleanField() last_login = serializers.DateTimeField() #一对一关系 #roles = serializers.CharField(source="roles.title") # 多对多,SerializerMethodField(),表示自定义显示 # 然后写一个自定义的方法 roles = serializers.SerializerMethodField() def get_roles( self ,row): role_obj = row.roles. all () ret = [] for i in role_obj: ret.append({ 'id' :i. id , 'title' :i.title}) return ret |
3 进阶序列化2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class UserSerializer(serializers.ModelSerializer): #一对一关系 #roles = serializers.CharField(source="roles.title") # 多对多,SerializerMethodField(),表示自定义显示 # 然后写一个自定义的方法 roles = serializers.SerializerMethodField() def get_roles( self ,row): role_obj = row.roles. all () ret = [] for i in role_obj: ret.append({ 'id' :i. id , 'title' :i.title}) return ret class Meta: model = models.Users fields = [ 'id' , 'username' , 'nick_name' , 'password' , 'roles' ] |
4 序列化进阶3,自动序列化连表
1 2 3 4 5 6 | class UserSerializer(serializers.ModelSerializer): class Meta: model = models.Users fields = "__all__" # 连表的深度 depth = 1 |
5 序列化进阶4,生成URL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class UserSerializer(serializers.ModelSerializer): roles = serializers.HyperlinkedIdentityField(view_name = 'roleId' ,many = True ,lookup_url_kwarg = 'id' ) class Meta: model = models.Users fields = "__all__" # 连表的深度 depth = 1class UsersView(APIView): def get( self ,request, * args, * * kwargs): ret = { 'code' : 1000 , 'msg' : None , 'data' : None } try : obj = models.Users.objects. all () #使用HyperlinkedIdentityField生成URL,这里必须要传参数context={'request':request} ser = rbac_serializers.UserSerializer(instance = obj, many = True ,context = { 'request' :request}) ret[ 'data' ] = ser.data except Exception as e: logger.error(e) return Response(ret) |
6 序列化进阶5,自定义验证规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #定义验证规则<br>class GroupValidation(object): def __init__( self ,base): self .base = base #__call__(),该方法的功能类似于在类中重载 () 运算符,使得类实例对象可以像调用普通函数那样,以“对象名()”的形式使用 def __call__( self , value): if not value.startswith( self .base): message = "标题必须以%s为开头" % self .base raise serializers.ValidationError(message) class UserGroupSerializer(serializers.Serializer):<br> #序列化中加入字段校验 title = serializers.CharField(validators = [GroupValidation( '以我开头' ),]) class UserGroupView(APIView): def post( self ,request, * args, * * kwargs): ser = UserGroupSerializer(data = request.data) if ser.is_valid(): print (ser.validated_data[ 'title' ]) else : print (ser.errors) return HttpResponse( "用户提交数据验证" ) |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步