标签:raise 定义数据 call 创建 djang ups res for django
# 方式一: publish_list = models.Publish.objects.all() # 导入序列化组件 from django.core import serializers serializers.serialize("json", publish_list)
# 方式二: # 为queryset和model对象做序列化 class PublishSerializers(serializers.Serializer): # 添加做序列化的字段 name = serializers.CharField() email = serializers.CharField() publish_list = models.Publish.objects.all() PublishSerializers(publish_list, many=True) PublishSerializers(model_obj)
Response
from rest_framework.response import Response
# 序列化 一对多 多对多 class BookSerializers(serializers.Serializer): # 添加做序列化的字段 title = serializers.CharField() price = serializers.CharField() # 一对多 publish = serializers.CharField(source="publish.name") # 多对多 authors = serializers.SerializerMethodField() def get_authors(self, obj): temp = [] for obj in obj.authors.all(): temp.append(obj.name)
# 等同于上面的 from rest_framework.views import APIView class BookModelSerializers(serializers.ModelSerializer): class Meta: model = Book # 表名 fields = "__all__" class BookView(APIView): def get(self, request): book_list = Book.objects.all() bs = BookModelSerializers(book_list, many=True) return Response(bs.data) def post(self): pass
class BookView(APIView): def get(self, request): ‘‘‘ 获取书籍 :param request: :return: ‘‘‘ book_list = Book.objects.all() bs = BookModelSerializers(book_list, many=True) return Response(bs.data) def post(self, request): ‘‘‘ 添加书籍 :return: ‘‘‘ # post请求的数据 bs = BookModelSerializers(data=request.data) if bs.is_valid(): bs.save() # 调用的是create方法 # 返回的是添加的数据 return Response(bs.data) else: # 错误的数据 return HttpResponse(bs.errors)
class BookModelSerializers(serializers.ModelSerializer): class Meta: model = Book # 表名 fields = "__all__" publish = serializers.CharField(source="publish.pk) # 针对一对多字段publish,会报错,所以重写create方法 def create(self, validated_data): book = Book.objects.create(title=validated_data["title"], price = validated_data["price"], pub_date = validated_data["pub_date"]) book.authors.add(*validated_data["authors"]) return book
class UserInfoSerializer(serializers.ModelSerializer): type = serializers.CharField(source="get_user_type_display") group = serializers.CharField(source="group.title") rls = serializers.SerializerMethodField() def get_rls(self, row): # 获取用户所有的角色 role_obj_list = row.roles.all() ret = [] # 获取角色的id和名字 # 以字典的键值对方式显示 for item in role_obj_list: ret.append({"id": item.id, "title": item.title}) return ret class Meta: model = models.UserInfo fields = [‘id‘,‘username‘,‘password‘,‘type‘,‘group‘,‘rls‘]
class UserInfoSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo #fields = "__all__" fields = [‘id‘,‘username‘,‘password‘,‘group‘,‘roles‘] #表示连表的深度 depth = 1
# urls.py urlpatterns = [ re_path(‘(?P<version>[v1|v2]+)/group/(?P<pk>\d+)/‘, GroupView.as_view(),name = ‘gp‘) #序列化生成url ]
class UserInfoSerializer(serializers.ModelSerializer): # 获取url group = serializers.HyperlinkedIdentityField(view_name=‘gp‘,lookup_field=‘group_id‘,lookup_url_kwarg=‘pk‘) class Meta: model = models.UserInfo #fields = "__all__" fields = [‘id‘,‘username‘,‘password‘,‘group‘,‘roles‘] #表示连表的深度 depth = 0
效果:
# 自定义验证规则 class GroupValidation(object): def __init__(self,base): self.base = base 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("用户提交数据验证")
标签:raise 定义数据 call 创建 djang ups res for django
原文地址:https://www.cnblogs.com/pgxpython/p/9961944.html