标签:extra 自定义 name 绑定 delete object 请求 date get
目录
# view.py
class UserV1ApiView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
user_dic = models.User.objects.filter(is_delete=False, pk=pk).values('username', 'sex', 'img').first()
if not user_dic:
return Response({
'status': 1,
'msg': 'pk error',
}, status=400)
user_dic['img'] = '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, user_dic.get('img'))
return Response({
'status': 0,
'msg': 'ok',
'results': user_dic
})
else:
user_query = models.User.objects.filter(is_delete=False).values('username', 'sex', 'img').all()
for user_dic in user_query:
user_dic['img'] = '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, user_dic.get('img'))
user_list = list(user_query)
return Response({
'status': 0,
'msg': 'ok',
'results': user_list
})
简单来说,序列化就是将数据给前台;反序列化就是完成数据库入库
视图类序列化过程:
# views.py
from . import serializers
class UserV2APIView(APIView):
# 单查群查
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
user_obj = models.User.objects.filter(is_delete=False, pk=pk).first()
if not user_obj:
return Response({
'status': 1,
'msg': 'pk error',
}, status=400)
user_ser = serializers.UserSerializer(user_obj, many=False) # many默认为False
user_obj_data = user_ser.data
return Response({
'status': 0,
'msg': 'ok',
'results': user_obj_data
})
else:
# 将对象对外提供的字段,已经整个序列化过程封装,形成序列化类
user_query = models.User.objects.filter(is_delete=False).all()
user_ser = serializers.UserSerializer(user_query, many=True)
user_list_data = user_ser.data
return Response({
'status': 0,
'msg': 'ok',
'results': user_list_data
})
# 序列化类 serializer.py
class UserSerializer(serializers.Serializer):
# 字段名与字段类型与model要一致
# 没有的字段不参与序列化给前端
# 可以自定义序列化,采用方法序列化,不建议自定义字段与数据库字段名重名
username = serializers.CharField()
gender = serializers.SerializerMethodField()
def get_gender(self, obj):
return obj.get_sex_display()
icon = serializers.SerializerMethodField()
def get_icon(self, obj):
return '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, obj.img)
视图类反序列化过程:
# views.py
class UserV2ApiView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
user_obj = models.User.objects.filter(is_delete=False, pk=pk).first()
if not user_obj:
return Response({
'status': 1,
'msg': 'pk error',
}, status=400)
user_ser = serializer.UserSerializer(user_obj, many=False)
user_obj.data = user_ser.data
return Response({
'status': 0,
'msg': 'ok',
'results': user_obj.data
})
else:
user_query = models.User.objects.filter(is_delete=False).all()
user_ser = serializer.UserSerializer(user_query, many=True)
user_list = user_ser.data
return Response({
'status': 0,
'msg': 'ok',
'results': user_list
})
def post(self, request, *args, **kwargs):
request_data = request.data
user_ser = serializer.UserDeSerializer(data=request_data)
if user_ser.is_valid():
user_obj = user_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializer.UserSerializer(user_obj).data
})
else:
return Response({
'status':1,
'msg': user_ser.errors
})
# 序列化类 serializer.py
class UserDeSerializer(serializers.Serializer):
username = serializers.CharField(max_length=10, min_length=2, error_messages={
'max_length': '太长',
'min_length': '太小'
})
password = serializers.CharField(max_length=10, min_length=2)
sex = serializers.BooleanField(required=False)
# 自定义校验字段:设置语法与系统字段没有区别,但是这些字段不能参与入库操作,需要在全局钩子中,将其取出
re_password = serializers.CharField(max_length=10, min_length=2)
# 局部钩子
def validate_username(self, value):
if 'y' in value:
raise serializers.ValidationError("名字中不能有y")
return value
# 全局钩子
def validate(self, attrs):
password = attrs.get('password')
re_password = attrs.pop('re_password')
if re_password != password:
raise serializers.ValidationError('两次密码不一致')
return attrs
# 在视图类中调用序列化类的save方法完成入库,Serializer类能做的就是 增 入库走create方法,改 入库走update方法
def create(self, validated_data):
return models.User.objects.create(**validated_data)
# instance要被修改的对象,validated_data代表校验后用来改instance的数据
def update(self, instance, validated_data):
# 用户名不能修改
validated_data.pop('username')
models.User.objects.filter(pk=instance.id).update(**validated_data)
return instance
局部钩子:
全局钩子:
validate_字段名(self, 字段值value)
ValidationError(‘错误信息‘)
validate(self, 所有字段值字典attrs)
# 模型类
class User(models.Model):
SEX_CHOICES = (
(0, '女'),
(1, '男')
)
username = models.CharField(max_length=64, blank=True, unique=True, verbose_name='姓名')
password = models.CharField(max_length=64, verbose_name='密码')
sex = models.IntegerField(choices=SEX_CHOICES, default=0, verbose_name='性别')
img = models.ImageField(upload_to='img', default='img/default.jpg', verbose_name='头像')
is_delete = models.BooleanField(default=False, verbose_name='是否注销')
created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
# 第二种自定义序列化字段(插拔式,提倡使用)
@property
def gender(self):
return self.get_sex_display()
@property
def icon(self):
from django.conf import settings
return '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, self.img)
class Meta:
db_table = 'table_user'
verbose_name_plural = '用户表'
def __str__(self):
return self.username
# views.py
class UserV3ApiView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
user_obj = models.User.objects.filter(is_delete=False, pk=pk).first()
if not user_obj:
return Response({
'status': 1,
'msg': 'pk error',
}, status=400)
user_ser = serializer.UserModelSerializer(user_obj, many=False)
return Response({
'status': 0,
'msg': 'ok',
'results': user_ser.data
})
else:
user_query = models.User.objects.filter(is_delete=False).all()
user_ser = serializer.UserModelSerializer(user_query, many=True)
return Response({
'status': 0,
'msg': 'ok',
'results': user_ser.data
})
def post(self, request, *args, **kwargs):
user_ser = serializer.UserModelSerializer(data=request.data)
if user_ser.is_valid():
user_obj = user_ser.save()
return Response({
'status': 0,
'msg': 'ok',
'results': serializer.UserModelSerializer(user_obj).data
})
else:
return Response({
'status': 1,
'msg': user_ser.errors
})
# 序列化类
class UserModelSerializer(serializers.ModelSerializer):
re_password = serializers.CharField(max_length=10, min_length=2, write_only=True)
class Meta:
model = models.User
fields = ('username', 'gender', 'icon', 'password', 'sex', 're_password')
extra_kwargs = {
'username': { # 系统字段不设置read_only和write_only,默认都参加
'min_length': 2,
'max_length': 10,
'error_messages': {
'min_length': '太短',
'max_length': '太长'
}
},
'gender': {
'read_only': True,
},
'password': {
'write_only': True
},
'sex': { # 像sex有默认值的字段,为选填字段('required': True可以将其变为必填字段)
'write_only': True
}
}
def validate_username(self, value):
if 'y' in value:
raise serializers.ValidationError('名字中不能有y')
return value
def validate(self, attrs):
password = attrs.get('password')
re_password = attrs.pop("re_password")
if password != re_password:
raise serializers.ValidationError('两次密码不一致')
return attrs
标签:extra 自定义 name 绑定 delete object 请求 date get
原文地址:https://www.cnblogs.com/setcreed/p/12099634.html