django-filter
drf
中如果想在url
中直接写过滤与排序,则需要安装第三方模块。
pip install django-filter
INSTALLED_APPS = [
'rest_framework','django_filters',]
准备工作
模型表
以下是一张书籍表和数据,我可能通过书名查,也可能通过价格查询。可能通过价格排序,也可能通过id
排序。
from django.db import models
# Create your models here.
class Book(models.Model):
book_id = models.AutoField(primary_key=True)
book_name = models.CharField(max_length=32)
book_price = models.IntegerField()
序列类
采用模型序列类:
from rest_framework import serializers
from app01.models import Book
class BookModelSerializers(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
视图
采用ListAPIView
:
from rest_framework.generics import ListAPIView
from app01.models import Book
from app01.ser import BookModelSerializers
class BookAPI(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializers
url
以下是url
的配置:
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/',admin.site.urls),path('books/',views.BookAPI.as_view()),]
过滤
局部配置
使用filter_backends
添加上过滤组件,并且使用filter_fields
指定可以过滤的字段。
from rest_framework.generics import ListAPIView
from django_filters.rest_framework import DjangoFilterBackend # 导入过滤组件
from app01.models import Book
from app01.ser import BookModelSerializers
class BookAPI(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializers
filter_backends = [DjangoFilterBackend] # 过滤组件导入
filter_fields = ("book_id","book_price") # 可以使用id过滤,也可以使用价格过滤
# http://127.0.0.1:8000/books/?book_price=128 只筛选出红楼梦
# 不支持大于、小于等操作
全局配置
全局配置:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
排序
局部配置
使用filter_backends
添加上排序组件,并且使用ordering_fields
指定可以过滤的字段。
注意在请求时要用ordering
作为key
进行请求:
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter # 导入排序
from app01.models import Book
from app01.ser import BookModelSerializers
class BookAPI(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializers
filter_backends = [OrderingFilter] # 排序组件导入
ordering_fields = ("book_id","book_price") # 可以使用id排序,也可以使用价格排序
# http://127.0.0.1:8000/books/?ordering=-book_price 加了- 号代表降序
# http://127.0.0.1:8000/books/?ordering=-book_id
全局配置
全局配置:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.OrderingFilter',)
}