共计 3283 个字符,预计需要花费 9 分钟才能阅读完成。
介绍
drf 框架是基于 Django 框架,用于疾速构建 Web RESTful API 的工具
官网文档:https://www.django-rest-framework.org/
装置:pip install djangorestframework
疾速应用
1. 搭建模型
from django.db import models
class BookModel(models.Model):
"""书籍模型"""
name = models.CharField(max_length=200, verbose_name='书籍名称')
book_info = models.TextField(max_length=1024, default=None, blank=True, verbose_name='书籍介绍')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创立工夫')
class Meta:
db_table = 'tb_book'
verbose_name = '书籍信息'
verbose_name_plural = verbose_name
class HeroModel(models.Model):
"""书籍人物模型"""
name = models.CharField(max_length=200, verbose_name='英雄姓名')
hero_info = models.TextField(max_length=1024, default=None, blank=True, verbose_name='英雄介绍')
join_time = models.DateTimeField(auto_now_add=True, verbose_name='退出工夫')
book_name = models.ForeignKey('BookModel', on_delete=models.CASCADE, related_name='book_hero', verbose_name='所属书籍')
class Meta:
db_table = 'tb_hero'
verbose_name = '书籍人物信息'
verbose_name_plural = verbose_name
- 留神外键对应关系
2. setting 配置
INSTALLED_APPS = [
......
'rest_framework',
]
3. 序列化器 serializer
# serializers.py
from rest_framework import serializers
from .models import BookModel, HeroModel
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = BookModel
fields = '__all__'
4. 视图 views
# views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from .serializers import BookSerializer
from .models import BookModel
class Books(GenericViewSet, ListModelMixin, CreateModelMixin):
queryset = BookModel.objects.all()
serializer_class = BookSerializer
5. 路由主动注册 DefaultRouter
from rest_framework.routers import DefaultRouter
from . import views
app_name = 'book'
urlpatterns = [
]
router = DefaultRouter()
router.register('book', views.Books, basename='book')
urlpatterns += router.urls
6. 成果显示
序列化关联返回 serializers
1. 返回关联外键的 ID:PrimaryKeyRelatedField
class BookSerializer(serializers.ModelSerializer):
book_hero = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
class Meta:
model = BookModel
fields = ['name', 'book_info', 'book_hero', 'create_time']
2. 返回关联字段模型的__str__办法的值:StringRelatedField
class BookSerializer(serializers.ModelSerializer):
book_hero = serializers.StringRelatedField(read_only=True, many=True)
class Meta:
model = BookModel
fields = ['name', 'book_info', 'book_hero', 'create_time']
3. 嵌套序列化器的应用
class BookSerializer(serializers.ModelSerializer):
# Heroserializer 应先于本序列化器前定义
book_hero = HeroSerializer(many=True)
class Meta:
model = BookModel
fields = ['name', 'book_info', 'book_hero', 'create_time']
4. read_only 和 write_only
read_only=True
:不参加反序列化验证 过程,只参加序列化返回过程write_only
:不参加序列化返回过程,只参加验证过程
5. 自定义验证办法(单 / 多字段验证)
-
繁多字段验证
class BookSerializer(serializers.ModelSerializer): book_hero = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = BookModel fields = ['name', 'book_info', 'book_hero', 'create_time'] def validate_name(self, value): """验证书名不能是 python""" if value == 'python': raise serializers.ValidationError('书名不能是 python') return value
-
多字段验证
def validate(self, attrs): if attrs['name'] == 'python' or attrs['book_info'] == 'python': raise serializers.ValidationError('书名或 info 不能是 python') return attrs
6. self.action 自定义装璜器应用
from rest_framework.decorators import action
class Books(GenericViewSet, ListModelMixin, CreateModelMixin):
queryset = BookModel.objects.all()
serializer_class = BookSerializer
@action(methods=['get'], detail=True)
def hello(self, request, pk):
res = 'hello' + str(pk)
return Response(res)
http://127.0.0.1:8000/book/1/hello/
正文完