其他分享
首页 > 其他分享> > djnago-filter用法

djnago-filter用法

作者:互联网

django-filter用法

集成drf

自定义filter文件内

from django_filters import rest_framework as rs_filters
from .models import *


class TestFilter(rs_filters.FilterSet):
    title = rs_filters.CharFilter(lookup_expr='icontains') # 不指定field_name默认用变量名去对应字段
    # title_name = rs_filters.CharFilter(lookup_expr='icontains', field_name='title')
    max_price = rs_filters.NumberFilter(field_name='price', lookup_expr='lte')
    min_price = rs_filters.NumberFilter(field_name='price', lookup_expr='gte')

    class Meta:
        model = Book
        fields = ['title', 'price']

在view.py内

from django_filters.rest_framework import DjangoFilterBackend
from .filter import TestFilter

class BookAPIView(ListAPIView):
    queryset = Book.objects
    serializer_class = BookSerializer
    filter_backends = [DjangoFilterBackend] # 必须用加DjangoFilterBackend或其子类
    filterset_class = TestFilter # 把自定义的过滤加上

image

标签:djnago,name,rs,price,用法,filter,filters,class
来源: https://www.cnblogs.com/zonghan/p/16583800.html