序列化器与视图
from rest_framework import serializers from .models import BookInfo, HeroInfo class BookInfoModelSerializer(serializers.ModelSerializer): """BookInfo模型类的序列化器""" class Meta: model = BookInfo # fields = '__all__' # fields = ['id', 'btitle', 'bpub_date'] # exclude = ('image',) fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment') extra_kwargs = { 'bread': {'min_value': 0, 'required': True}, 'bcomment': {'min_value': 0, 'required': True}, } class HeroInfoModelSerializer(serializers.ModelSerializer): class Meta: model = HeroInfo fields = ['id', 'hname', 'hbook'] depth = 1 def about_django(value): if 'django' not in value.lower(): raise serializers.ValidationError("图书不是关于Django的") class BookInfoSerializer(serializers.Serializer): """图书数据序列化器""" id = serializers.IntegerField(label='ID', read_only=True) btitle = serializers.CharField(label='名称', max_length=20, validators=[about_django]) bpub_date = serializers.DateField(label='发布日期', required=False) bread = serializers.IntegerField(label='阅读量', required=False) bcomment = serializers.IntegerField(label='评论量', required=False) image = serializers.ImageField(label='图片', required=False) heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # 新增 def validate_btitle(self, value): """单个字段验证""" if 'django' not in value.lower(): raise serializers.ValidationError("图书不是关于Django的") return value def validate(self, attrs): """多字段联合验证""" bread = attrs['bread'] bcomment = attrs['bcomment'] if bread < bcomment: raise serializers.ValidationError('阅读量小于评论量') return attrs def create(self, validated_data): """新建""" return BookInfo.objects.create(**validated_data) def update(self, instance, validated_data): """更新,instance为要更新的对象实例""" instance.btitle = validated_data.get('btitle', instance.btitle) instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date) instance.bread = validated_data.get('bread', instance.bread) instance.bcomment = validated_data.get('bcomment', instance.bcomment) instance.save() return instance class HeroInfoSerializer(serializers.Serializer): """英雄数据序列化器""" GENDER_CHOICES = ( (0, 'male'), (1, 'female') ) id = serializers.IntegerField(label='ID', read_only=True) hname = serializers.CharField(label='名字', max_length=20) hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False) hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True) hbook = serializers.PrimaryKeyRelatedField(label='图书', read_only=True)
from django.shortcuts import render from django.views.generic import View from django.http import JsonResponse, HttpResponse import json from datetime import datetime from rest_framework.viewsets import ModelViewSet from .models import BookInfo from . import serializers # Create your views here. """ GET /books/ 提供所有记录 POST /books/ 新增一条记录 GET /books/<pk>/ 提供指定id的记录 PUT /books/<pk> 修改指定id的记录 DELETE /books/<pk>/ 删除指定id的记录 响应数据 JSON """ class BookInfoViewSet(ModelViewSet): """使用DRF实现增删改查的后端API""" # 指定查询集 queryset = BookInfo.objects.all() # 指定序列化器 serializer_class = serializers.BookInfoSerializer class BooksAPIView(View): def get(self, request): """提供所有记录 GET /books/ """ # 查询所有记录 books = [BookInfo,BookInfo,BookInfo,BookInfo,BookInfo] books = BookInfo.objects.all() # 将模型列表转成字典列表 book_list = [] for book in books: book_list.append({ 'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else '' }) # 响应JSON数据 return JsonResponse(book_list, safe=False) def post(self, request): """新增一条记录 POST /books/ """ # 读取客户端传入的JSON数据 json_bytes = request.body json_str = json_bytes.decode() book_dict = json.loads(json_str) # 创建新的记录 book = BookInfo.objects.create( btitle=book_dict.get('btitle'), bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date(), bread = book_dict['bread'], bcomment = book_dict['bcomment'] ) # 构造响应数据 response_book_dict = { 'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else '' } # 响应结果 return JsonResponse(response_book_dict, status=201) class BookAPIView(View): def get(self, request, pk): """提供指定id的记录 GET /books/<pk>/ """ # 判断pk是否合法 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) # 构造响应数据 response_book_dict = { 'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else '' } # 响应结果 return JsonResponse(response_book_dict) def put(self, request, pk): """修改指定id的记录 PUT /books/<pk> """ # 判断pk是否合法 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) # 读取客户端传入的JSON数据 json_bytes = request.body json_str = json_bytes.decode() book_dict = json.loads(json_str) # 修改记录 book.btitle = book_dict.get('btitle') book.save() # 构造响应数据 response_book_dict = { 'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else '' } # 响应结果 return JsonResponse(response_book_dict) def delete(self, request, pk): """删除指定id的记录 DELETE /books/<pk>/ """ # 判断pk是否合法 try: book = BookInfo.objects.get(id=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) # 删除 book.delete() # 响应 return HttpResponse(status=204)