ModelViewSet
一.创建项目
1.创建 项目 :
django-admin startprojet drf
2. 创建 两个app ------ app1 ,book
python manage.py startapp app1
python manage.py startapp book
- settings 配置 ,一定不能少了 rest_framework 这个app的注册。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'book',
'app1',
]
连接数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'book', # 数据库名
'HOST':'127.0.0.1',
'PORT':3306,
'USER':'root',
'PASSWORD':'123' # 这里必须为字符串
}
}
- 主应用中 init.py 文件中:
import pymysql
pymysql.install_as_MySQLdb()
5. bookapp 中的 model.py 中建表
from django.db import models
Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32,verbose_name='书名')
pub_date = models.DateField(verbose_name='出版日期')
bread = models.IntegerField(verbose_name='阅读量')
bcomment = models.IntegerField(verbose_name='评论数')
class Meta:
db_table ='book'
def __str__(self):
return self.title
class Hero(models.Model):
name = models.CharField(max_length=32,verbose_name='名字')
age = models.IntegerField(verbose_name='年龄')
class Meta:
db_table='人物'
def __str__(self):
return self.name
- 数据库迁移。
python manage.py makemigrations
python manage.py migrate
- 在表中录入数据。
接口实现
1.在app1 先创建serializers.py 文件
from rest_framework import serializers
from book.models import Book,Hero
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields='__all__'
# 可以给模型序列化器里面指定的字段设置限制选项
extra_kwargs = {
'bread':{'min_value':0,'required':True}
}
class HeroModelSerializer(serializers.ModelSerializer):
class Meta:
model = Hero
fields = '__all__'
- app1 views.py 创建视图
from django.shortcuts import render
Create your views here.
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from app1.serializers import BookModelSerializer, HeroModelSerializer
from book.models import Book, Hero
class BookModelViewSet(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
@action(methods=['get'],detail=False)#detail=False 是否为详情页数据
def get_top_5(self,request): # 其接口 http://127.0.0.1:8000/app1/book/get_top_5/
# 获取阅读量最多的5条数据
books = Book.objects.order_by('-bread')[:5] # 取阅读量为前5的书籍
serializer = BookModelSerializer(instance=books,many=True)
return Response(serializer.data)
# action是drf提供的路由和视图方法绑定关系的装饰器
# from rest_framework.decorators import action
# 参数1: methods 列表,设置视图方法允许哪些http请求访问进来
# 参数2: detail 当前是否方法是否属于详情页视图,
# False,系统不会自动增加pk在生成的路由地址中
# True 则系统会自动增加pk在生成的路由地址
@action(methods=['get','post'],detail=True)
def get_one_title(self,request,pk):
book = Book.objects.get(pk=pk)
return Response(book.btitle)
class HeroModelViewSet(ModelViewSet):
queryset = Hero.objects.all()
serializer_class = HeroModelSerializer
- 配置路由
1.app1 应用下创建一个路由文件 urls.py
from rest_framework import routers
from app1.views import BookModelViewSet, HeroModelViewSet
urlpatterns=[]
router = routers.DefaultRouter() # 开发环境用,有主界面
router = routers.SimpleRouter() # 生产环境用
router.register('book',BookModelViewSet)
router.register('hero',HeroModelViewSet)
urlpatterns += router.urls
2.主应用下 urls.py 文件中
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/',include('app1.urls'))
]