DRF的ModelSerializer的使用

2022-07-12 05:21:10 字數 2363 閱讀 8661

在views中新增

from django.shortcuts import

render

#create your views here.

from rest_framework.views import

apiview

from rest_framework.response import

response

user

from .serializers import *

from rest_framework.viewsets import

modelviewset

class

userview(apiview):

defget(self, request):

user_obj =user.objects.all()

ser = userser(user_obj, many=true)

return

response(ser.data)

from rest_framework.viewsets import

modelviewset

from django_filters.rest_framework import

djangofilterbackend

from rest_framework.filters import orderingfilter #

排序導包

from rest_framework.pagination import

pagenumberpagination

class

paginotorview(pagenumberpagination):

page_size_query_param = '

page_num

'max_page_size = 3

class usermodelview(modelviewset): #

繼承modelviewset

queryset = user.objects.all() #

查詢集 serializer_class = userser #

序列化器

pagination_class = paginotorview #

分頁 filter_fields = ['

name

', '

age','

home

'] #

設定要查尋的字段

filter_backends =[orderingfilter,djangofilterbackend]

ordering_fields = ['

age'] #

查詢格式: &ordering=age

在serlizers中新增

from rest_framework.serializers import

modelserializer

from .models import *

class

userser(modelserializer):

class

meta:

model =user

fields = '

__all__'#

depth = 1 # 查詢展示外來鍵內容,後面的數字代表展示幾層外來鍵

在urls.py中新增

#

-*- coding: utf-8 -*-

from django.urls import

path,include

from .views import *

from rest_framework.routers import defaultrouter #

導包router = defaultrouter() #

例項化router.register('

user02

',usermodelview) #

註冊urlpatterns =[

path(

'user/

',userview.as_view()),

path(

'',include((router.urls))), #

把上面寫的路由註冊進來

關於drf的元件

關於版本控制項 賦值 reques.version request.versioning scheme from rest framework.versioning import acceptheaderversioning 檢視原始碼 重點 重寫 determine version request...

drf的許可權擴充

drf框架為我們提供了基本的許可權驗證。主要包括三種驗證 1 allowany 所有使用者 2 isauthenticated 驗證過的使用者 3 isadminuser 超級管理員 這些許可權人員不一定滿足專案的許可權需求。那麼如果我們想定義新的許可權,需要繼承basepermission 定義新...

DRF基本使用

執行pip install djangorestframework安裝drf 1.查詢 books book.objects.all 2.資料轉換 jsonresponse book list,safe false 為什麼加safe false?檢視原始碼可知,safe預設時且非dict型別時會丟擲...