django-filter
提供一种简单的方式为用户提供的参数(url传参)来过滤queryset
model
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField()
description = models.TextField()
release_date = models.DateField()
manufacturer = models.ForeignKey(Manufacturer)
filter
import django_filters
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['price', 'release_date']
url参数:price
release_date
匹配模式:完全匹配
重写某个字段的过滤
import django_filters
class ProductFilter(django_filters.FilterSet):
price = django_filters.NumberFilter(lookup_type='lt')
class Meta:
model = Product
fields = ['price', 'release_date']
url参数:price
release_date
匹配模式:price
小于输入值,release_date
精确匹配
附:
lt
小于
lte
小于等于
gt
大于
gte
大于等于
重写一个CharField
类型字段的过滤
class ProductFilter(django_filters.FilterSet):
filter_overrides = {
models.CharField: {
'filter_class': django_filters.CharFilter,
'extra': lambda f: {
'lookup_type': 'icontains',
}
}
}
class Meta:
model = Product
fields = ['name']
url参数:name
匹配模式:完全匹配
import django_filters
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = {'price': ['lt', 'gt'],
'release_date': ['exact'],
}
url参数:price__lt
price__gt
release_date
exact
是默认的
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['manufacturer__country']
类视图
# urls.py
from django.conf.urls import patterns, url
from django_filters.views import FilterView
from myapp.models import Product
urlpatterns = patterns('',
(r'^list/$', FilterView.as_view(model=Product)),
)
需要提供一个模版名字为<app>/<model>_filter.html
,在模版里可以获取名为object_list
的Product
QuerySet
方法视图
虽然现在建议使用,但对针方法视图也有对应的方法
# urls.py
from django.conf.urls import patterns, url
from myapp.models import Product
urlpatterns = patterns('',
(r'^list/$', 'django_filters.views.object_filter', {'model': Product}),
)
http://django-filter.readthedocs.org/en/latest/index.html