案例:
实现过程:
1. 创建一个项目:
django-adim startproject dfr3
2. 创建 一个app homwork
python manage.py startapp homework
3. settings.py
必须注册 rest_framework
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'homework', ]
连接数据库:
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()
serilazers.py 文件中
from rest_framework import serializers from homework.models import Province class ProvinceModelSerilazers(serializers.ModelSerializer): class Meta: model = Province fields ='__all__' # 序列化器 2 只显示 id 和name 字段 class Province2ModelSerilazers(serializers.ModelSerializer): class Meta: model = Province fields =['id','name']
views.py
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet from .serilazers import ProvinceModelSerilazers,Province2ModelSerilazers from .models import Province class ProvinceModelViewSet(ModelViewSet): queryset = Province.objects.all() serializer_class = ProvinceModelSerilazers @action(methods=['get',],detail=False) def get_gdp_top3(self,request): '''查gdp前3的省份''' # datas= Province.objects.all().order_by('-gdp')[:3] # serializer = ProvinceModelSerilazers(instance=datas,many=True) datas =self.get_queryset().order_by('-gdp')[:3] serializer = self.get_serializer(instance=datas,many=True) return Response(serializer.data) class ProvinceReadOnlyModelViewSet(ReadOnlyModelViewSet): queryset = Province.objects.all() # serializer_class = ProvinceModelSerilazers def get_serializer_class(self): if self.action=='list': return Province2ModelSerilazers # 当获取所有页只返回两个字段 else: return ProvinceModelSerilazers # 当获取详情页是返回所有字段
路由
1. homework 视图中 urls.py 路由
from django.urls import path,re_path from rest_framework.routers import DefaultRouter from homework import views urlpatterns=[] router = DefaultRouter() router.register('province',views.ProvinceModelViewSet) router.register('prov',views.ProvinceReadOnlyModelViewSet) urlpatterns += router.urls
2、总路由
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('hw/', include('homework.urls')), ]