- *** 作有5个:
增加一个数据post,删除一个数据delete,查询所有数据get,查询一个数据get,修改一个数据put - 有些需要参数、而有些不需要参数
不需要参数:增加一个数据post,查询所有数据get 静态路由
需要参数:删除一个数据delete,查询一个数据get,修改一个数据put 带id的动态路由 - 只需要2个视图就可已完成
- 首先在子应用里创建一个serializers.py文件,编写序列化器
from rest_framework import serializers
class PeopleSerializer(serializers.Serializer):
# id = serializers.IntegerField()
name = serializers.CharField(max_length=20)
age = serializers.IntegerField()
sex = serializers.CharField(max_length=20)
- 图层写入方法
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import People
from myapp.serializers import PeopleSerializer
# 查看所有信息
class PeopleView(APIView):
def get(self, request):
people_data = People.objects.all()
ser = PeopleSerializer(people_data, many=True)
# .data必须加 status=200 返回状态码
return Response(ser.data, status=200)
# 增加数据
def post(self, request):
ser = PeopleSerializer(data=request.data)
# 判断是否报错
if ser.is_valid(raise_exception=True):
# 保存
ser.save()
return Response({'mag': 'success'}, status=201)
return Response({'msf': 'error'}, status=400)
- 增加数据还需要在serializers文件内写入方法
def create(self, validated_data):
obj = People.objects.create(
**validated_data
)
return obj
- 编写静态路由
path('peo/', views.PeopleView.as_view()),
3. 查看一个信息、修改数据和删除数据
- 编写动态视图
class Peopleviews2(APIView):
# 获取一个数据
def get(self, request, id):
try:
peo_data = People.objects.get(id=id)
except Exception as a:
print(a)
return Response({'msg': 'error'}, status=404)
ser = PeopleSerializer(peo_data)
return Response(ser.data, status=200)
# 修改数据
def put(self, request, id):
try:
upd_data = People.objects.get(id=id)
except Exception as a:
print(a)
return Response({'msg': 'error'}, status=400)
ser = PeopleSerializer(instance=upd_data, data=request.data)
if ser.is_valid(raise_exception=True):
ser.save()
return Response({"msg": 'success'}, status=201)
return Response({'msg': 'error'}, status=400)
# 删除数据
def delete(self, request, id):
try:
del_data = People.objects.get(id=id)
except Exception as a:
print(a)
return Response({'msg': 'error'}, status=400)
del_data.delete()
return Response({'msg': 'success'}, status=204)
- 修改数据还需要在serializers文件内写入方法
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
instance.age = validated_data.get('age')
instance.sex = validated_data.get('sex')
instance.save()
return instance
- 编写动态路由
path('peo//' , views.Peopleviews2.as_view())
4. 模型序列化器
class PeopleSerializer2(serializers.ModelSerializer):
class Meta:
model = People
fields = '__all__'
在serializers文件中定义了序列化器后就不用定义之前的方法了
5. 模型序列化器配置class GoodsSer(serializers.ModelSerializer):
class Meta:
model = Goods
fields = '__all__' # 指明所有模型类字段
# exclude = ('createtime',) # 排除掉的字段
# read_only_fields = ('title','description') # 只用于序列化的字段
# fields = ('title','description','inventory') # 手动指明字段
# extra_kwargs = {
# 'price':{'min_value':0, 'required':True},
# } # 修改原有字段的选项参数
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)