标签:link base 必须 ups 方法 def 提交 dep 关系
1 序列化入门
class RoleSerializer(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField() label = serializers.CharField()
2 进阶序列化1
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
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,自动序列化连表
class UserSerializer(serializers.ModelSerializer): class Meta: model = models.Users fields = "__all__" # 连表的深度 depth = 1
5 序列化进阶4,生成URL
class UserSerializer(serializers.ModelSerializer): roles = serializers.HyperlinkedIdentityField(view_name=‘roleId‘,many=True,lookup_url_kwarg=‘id‘) class Meta: model = models.Users fields = "__all__" # 连表的深度 depth = 1
class 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,自定义验证规则
#定义验证规则
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):
#序列化中加入字段校验 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("用户提交数据验证")
标签:link base 必须 ups 方法 def 提交 dep 关系
原文地址:https://www.cnblogs.com/xiao2er/p/13292036.html