restful 序列化

用rest_framework快速实现图书的增删改查操作

一、创建django项目  并在setting.py下的installed_app中注册rest_framework;

二、在models中创建数据模型:

from django.db import models

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish = models.ForeignKey(to='Publish', to_field='id', on_delete=models.CASCADE)
    author = models.ManyToManyField(to='Author')


class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20)
    city = models.CharField(max_length=32)
    email = models.EmailField()


class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20)
    age = models.IntegerField()
View Code

三、在views.py中(可以写到一个专门的序列化文件中)通过继承rest_framework下的serializers.ModelSerializer类来自定义序列化类:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
        # 指定要序列化的字段
        # fields=['nid','name']
        # 选择要排除的字段(注意,不能跟fields连用)
        # exclude=['name','price']
        # 深度,官方建议最多写10,建议最多写3
        depth = 1  
     # 局部钩子与全局钩子的使用,类似于form组件中的局部钩子于全局钩子
     # 局部钩子函数,对单个字段校验
     #校验name字段不能以sb开头
     #def validate_name(self,value):
     #    if value.startswith('sb'):
             #不能让你过
     #        raise ValidationError('书名不能以sb开头')
     #   else:
     #       return value

     #全局钩子函数,对全局字段进行校验
     # def validate(self,a):
     #     # print(a)
     #     name=a.get('name')
     #     price=a.get('price')
     #     if name != price:
     #         raise ValidationError('错了')
     #     else:
     #         return a     
View Code

 四、在views.py中通过来实现具体的增删改查:

from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework import serializers
from app01.models import *
from rest_framework.views import APIView


# class AuthorSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Author
#         fields = '__all__'


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'



class Booksview(APIView):
    def get(self, request, *args, **kwargs):
        respones = {'status': 100, 'msg': '查询成功'}
        book_list = Book.objects.all()
        book_ll = BookSerializer(instance=book_list, many=True)
        respones['data'] = book_ll.data
        return Response(respones)

    def post(self, request, *args, **kwargs):
        respones = {'status': 100, 'msg': '新增成功'}
        book = BookSerializer(data=request.data, many=False)
        if book.is_valid():
            book.save()
            respones['data'] = book.data
        else:
            respones['msg'] = book.errors
        return Response(respones)


class Bookview(APIView):
    def get(self, request, pk, *args, **kwargs):
        respones = {'status': 100, 'msg': '查询成功'}
        book_list = Book.objects.filter(pk=pk)
        book_ll = BookSerializer(instance=book_list, many=True)
        respones['data'] = book_ll.data
        return Response(respones)

    def put(self, request, pk, *args, **kwargs):
        respones = {'status': 100, 'msg': '修改成功'}
        book = Book.objects.filter(pk=pk).first()
        book_ll = BookSerializer(instance=book, data=request.data)
        if book_ll.is_valid():
            book_ll.save()
            respones['data'] = book_ll.data
        else:
            respones['msg'] = book_ll.errors
        return Response(respones)

    def delete(self, request, pk, *args, **kwargs):
        book = Book.objects.filter(pk=pk).delete()
        return HttpResponse("")

# 代码可精简
View Code

五、路由层urls的配置:

#  django  2.x版本

from django.contrib import admin
from django.urls import path, re_path   # re_path相当于1.x版本中的url
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^books/$', views.Booksview.as_view()),
    re_path('^books/(?P<pk>\d+)', views.Bookview.as_view()),
]
View Code

 

转载于:https://www.cnblogs.com/peng-zhao/p/10602604.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值