一.過濾Filtering
對於列表數據可能需要根據字段進行過濾,我們可以通過添加django-fitlter擴展來增強支持。
需要安裝:
pip install django-filter
安裝完成之後需要註冊到INSTALLED_APPS中:
'django_filters', #過濾
示例:
class StudentListAPIView(ListAPIView):
serializer_class = StudentModelserializers
queryset = Student.objects.all()
filter_fields = ['age'] # 根據age查找需要的數據
請求方式:
http://127.0.0.1:8000/testhome/page_home/?age=22
結果:
二.排序
對於列表數據,REST framework提供了OrderingFilter過濾器來幫助我們快速指明數據按照指定字段進行排序。
使用方法:
在類視圖中設置filter_backends,使用rest_framework.filters.OrderingFilter
過濾器,REST framework會在請求的查詢字符串參數中檢查是否包含了ordering參數,如果包含了ordering參數,則按照ordering參數指明的排序字段對數據集進行排序。
前端可以傳遞的ordering參數的可選字段值需要在ordering_fields中指明。
示例:
class StudentListAPIView(ListAPIView):
serializer_class = StudentModelserializers
queryset = Student.objects.all()
# 排序
filter_backends = [OrderingFilter,DjangoFilterBackend]
ordering_fields = ['id','age']
請求方式:
http://127.0.0.1:8000/home/student_list/?ordering=age
# 如果有數據重複 可以指定其他字段再排序
# age 數據重複 根據id倒序排列
# http://127.0.0.1:8000/home/student_list/?ordering=age,-id
三.分頁PageNumberPagination
REST framework提供了分頁的支持。
可以在settings.py中配置:
缺點:只要有listapiview 全部都會分頁
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100 # 每頁數目
}
注意:如果在視圖內關閉全局分頁功能,只需在視圖內設置
pagination_class = None
局部配置:
from rest_framework.pagination import PageNumberPagination
class CustomPage(PageNumberPagination):
# 頁面展示最大幾條
max_page_size = 3
# 默認展示幾條
page_size = 2
# 頁數關鍵字 值是頁碼
page_query_param = 'page'
# 每頁數目關鍵字 最大是上面的max_page_size
page_size_query_param = 'page_size'
視圖集中使用:
class StudentListAPIView(ListAPIView):
serializer_class = StudentModelserializers
queryset = Student.objects.all()
# 分頁
pagination_class = CustomPage
四.異常處理Exceptions
REST framework提供了異常處理,我們可以自定義異常處理函數。
# 數據庫異常
from rest_framework.views import exception_handler
from rest_framework import status
from django.db import DatabaseError
from rest_framework.response import Response
def custom_excepton(exc, context):
response = exception_handler(exc, context)
if response is None:
if isinstance(exc,DatabaseError):
response = Response({'error':'服務器錯誤!!!!'},status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
在配置文件中聲明自定義的異常處理:寫路徑就行
# 自定義異常
'EXCEPTION_HANDLER': 'drfdemo.utils.exceptions.custmoer_exceptions',
REST framework定義的異常
- APIException 所有異常的父類
- ParseError 解析錯誤
- AuthenticationFailed 認證失敗
- NotAuthenticated 尚未認證
- PermissionDenied 權限決絕
- NotFound 未找到
- MethodNotAllowed 請求方式不支持
- NotAcceptable 要獲取的數據格式不支持
- Throttled 超過限流次數
- ValidationError 校驗失敗
也就是說,很多的沒有在上面列出來的異常,就需要我們在自定義異常中自己處理了。
五.自動生成接口文檔
REST framework可以自動幫助我們生成接口文檔。
接口文檔以網頁的方式呈現。
自動接口文檔能生成的是繼承自APIView
及其子類的視圖。
安裝第三方庫:
pip install coreapi
配置文件加上這句:
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'
urls.py配置:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('docs/', include_docs_urls(title='站點頁面標題'))
]
訪問接口文檔網頁:
六.Xadmin
xadmin是Django的第三方擴展,比使用Django的admin站點更強大也更方便。
文檔:https://xadmin.readthedocs.io/en/latest/index.html
安裝:
pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
配置文件:
INSTALLED_APPS = [
...
'xadmin',
'crispy_forms',
'reversion',
...
]
執行數據庫遷移指令:
python manage.py makemigrations
python manage.py migrate
添加路由信息:
import xadmin
xadmin.autodiscover()
# version模塊自動註冊需要版本控制的 Model
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
path(r'xadmin/', xadmin.site.urls),
]
使用:
- xadmin不再使用Django的admin.py,而是需要編寫代碼在adminx.py文件中。
- xadmin的站點管理類不用繼承
admin.ModelAdmin
,而是直接繼承object
即可。
例如:在子應用中創建adminx.py文件。
全局配置+頁面樣式控制:
import xadmin
from xadmin import views
from student.models import Student
class BaseSetting(object):
"""xadmin的基本配置"""
enable_themes = True # 開啓主題切換功能
use_bootswatch = True
xadmin.site.register(views.BaseAdminView, BaseSetting)
class GlobalSettings(object):
"""xadmin的全局配置"""
site_title = "test" # 設置站點標題
site_footer = "test" # 設置站點的頁腳
menu_style = "accordion" # 設置菜單摺疊
xadmin.site.register(views.CommAdminView, GlobalSettings)
class StudentAdmin(object):
list_display = ['id','name','sex','age','class_null','description'] # 展示字段
search_fields = ['name','class_null'] # 搜索字段
list_filter = ['sex','age'] # 過濾器
ordering = ['age'] # 按照age排序 升序
show_detail_fields = ['name'] # 顯示name字段的詳細信息
# list_editable = ['age','sex'] # 頁面上可以編輯的字段
refresh_times = [5,10,30,60] # 指定列表頁的定時刷新
list_export = ['xls', 'xml', 'json'] # 導出的格式
list_export_fields = ['id', 'name', 'age'] # 導出的字段
show_bookmarks = True # 是否隱藏書籤功能
data_charts = { # 圖標
"members": {
'title': '會員的年齡分佈',
"x-field": "age",
"y-field": ['age'],
"order": ('age',)
},
# 支持生成多個不同的圖表
# "order_amount": {
# 'title': '圖書發佈日期表',
# "x-field": "bpub_date",
# "y-field": ('btitle',),
# "order": ('id',)
# },
}
model_icon = 'fa fa-gift' # 修改標題圖標
readonly_fields = ['class_null','age'] # 編輯時只讀字段 編輯時不可修改
exclude = ['id'] # 編輯時隱藏的字段
xadmin.site.register(Student,StudentAdmin)