serializers文件配置
from rest_framework import serializers
from .models import *
class ClassroomSerializer(serializers.Serializer):
class_name = serializers.CharField(max_length=32, required=True, label='班级名')
address = serializers.CharField(max_length=32, label='地址')
# 添加
def create(self, validated_data):
return Classroom.objects.create(**validated_data)
# 修改
def update(self, instance, validated_data):
instance.class_name = validated_data.get('class_name', instance.class_name)
instance.address = validated_data.get('address', instance.address)
instance.save()
return instance
# 验证
def validate(self, attrs):
if attrs.get('address') != 'beijing':
raise serializers.ValidationError('信息不在北京')
return attrs
View视图配置
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from .serializer import *
class PageNum(PageNumberPagination):
# 指定查询字符串中代表每页返回数据数量的参数名,默认None
page_size_query_param = "max_page"
# 指定查询字符串中代表页码的参数名,不指定默认值page
# page_query_param = 'page'
# max_page_size = 10 # 一页最多的结果条数,
class ClassroomView(APIView):
def get(self, request):
class_obj = Classroom.objects.all().order_by('-id')
# 分页
paginator = PageNum()
result_page = paginator.paginate_queryset(class_obj, request)
ser_obj = ClassroomSerializer(result_page, many=True)
return Response(ser_obj.data)
def post(self, request):
data = request.data
# 验证地址是不是beijing
if data['address'] != 'beijing':
return Response({'msg': '信息不在北京'})
ser_obj = ClassroomSerializer(data=data)
if ser_obj.is_valid():
ser_obj.save()
return Response(ser_obj.data)
else:
return Response(ser_obj.errors)
def put(self, request):
data = request.data
# 查询要修改的对象
instance = Classroom.objects.filter(class_name=data['class_name']).first()
# 序列化修改
ser_obj = ClassroomSerializer(instance=instance, data=data)
if ser_obj.is_valid():
ser_obj.save()
return Response(ser_obj.data)
else:
return Response(ser_obj.errors)
view多对多serializers原始添加
**
- sers部分
**
class UserSer(serializers.Serializer):
"""
添加用户使用serializers
"""
username=serializers.CharField(max_length=20)
age=serializers.IntegerField()
home=serializers.CharField(max_length=20)
hight=serializers.IntegerField()
classrooms=serializers.IntegerField(write_only=True)
roles=serializers.ListField(write_only=True)
def create(self, validated_data):
#获取当前roles里的数据
data=validated_data.pop('roles')
#用classrooms_id来创建用户信息
user_obj=User.objects.create(classrooms_id=validated_data.pop('classrooms'),**validated_data)
#查看所有角色信息
role_obj=Role.objects.filter(id__in=data)
#角色信息添加
user_obj.roles.add(*role_obj)
return user_obj
**
- View视图部分
**
#serializers添加角色
# def post(self,request):
# data=request.data
# ser=UserSer(data=data)
# if ser.is_valid():
# ser.save()
# return Response({'msg':'添加成功','code':200})
# else:
# return Response({'error':ser.errors})