程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django rest framework---- filtering

編輯:Python

Django REST Framework---- Route matching

  • One 、 function
  • Two 、 Installation and configuration
  • 3、 ... and 、 Filter class ( New file filter.py)
  • Four 、 Add in view
  • 5、 ... and 、 Fuzzy query
  • 6、 ... and 、 Period of time

One 、 function

Filter a field
notes : Not all fuzzy filters are exact matches .

Two 、 Installation and configuration

  1. install
pip install django-filter==21.1

notes : The version is 21.1, Other versions cannot be used
2. To configure
stay settings.py Medium INSTSLL_APPS add to

'django_filters',

3、 ... and 、 Filter class ( New file filter.py)

from django_filters import FilterSet
from .models import Library name
class Library name Filter(FilterSet):
class Meta:
model = Faculty
fields = (' Field ',)
# notes : Fields to filter 

Four 、 Add in view

from django_filters.rest_framework import DjangoFilterBackend
from .filter import Library name Filter
class Library name ViewSet(ModelViewSet):
queryset = Library name .objects.all()
serializer_class = Library name Serializer
filter_backends = (DjangoFilterBackend,)
# Set up... For personalized views , You can also set it globally 
filter_class = Library name Filter

Global settings filter_backends

# stay settings.py Add 
REST_FRAMEWORK = {

'DEFAULT_FILTER_BACKENDS':[
'django_filters.rest_framework.DjangoFilterBackend',
],
}

5、 ... and 、 Fuzzy query

notes : Rewrite the filter code in the filter class

from django_filters import FilterSet,filters
from .models import Library name
#filters Is a fuzzy query class 
class FacultyFilter(FilterSet):
Field name = filters.CharFilter(field_name=' Field name ',lookup_expr='icontains')
class Meta:
model = Library name
fields = (' Field name ',)

6、 ... and 、 Period of time


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved