您可以使用以下内容创建自定义筛选器:
from django_filters import FilterSet, NumberFilter
class MyFilterSet(FilterSet):
user_age = NumberFilter(field_name='user_age', method='filter_user_age')
def filter_user_age(self, queryset, name, value):
return queryset.objects.filter(min_age__lte=value, max_age__gte=value)
或对于可为null的:
from django.db.models import Q
from django_filters import FilterSet, NumberFilter
class MyFilterSet(FilterSet):
user_age = NumberFilter(field_name='user_age', method='filter_user_age')
def filter_user_age(self, queryset, name, value):
return queryset.objects.filter(
Q(min_age=None) | Q(min_age__lte=value),
Q(max_age=None) | Q(max_age__gte=value),
)