Django通过两个字段范围过滤

l2osamch  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(140)

我有一个模型,有两个字段:min_agemax_age。我需要用Django过滤器过滤它,通过两个字段的范围。我怎么做?

# models.py

class AdvertisementModelMixin(models.Model):
    min_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )
    max_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )

字符串

dsekswqp

dsekswqp1#

您可以使用以下命令创建自定义筛选器:

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)

字符串
对于nullable:

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),
        )

相关问题