使用django_filters创建OR过滤器

时间:2015-02-24 16:34:29

标签: django filter django-queryset django-filter

我想在django_filters中创建一个OR过滤器。 所有过滤器都是完美的,除了我的产品名称。

我有一个搜索框,需要在列name_nl,name_en和name_fr中搜索产品名称。

如何使用Django_filter创建或过滤?

class ProductFilter(django_filters.FilterSet):
status = django_filters.CharFilter(name='productvariant__status_id', lookup_type='exact')
productname = django_filters.CharFilter(name='name_nl', lookup_type='icontains')

class Meta:
    model = Product
    fields = {
        'productname': ['icontains'],
        'status': ['exact']
    }

3 个答案:

答案 0 :(得分:3)

你可以这样做。

import django_filters
from django.db.models import Q

from app.models import User

class UserFilter(django_filters.FilterSet):

    q = django_filters.MethodFilter()

    class Meta:
        model = User
        fields = []

    def filter_q(self, queryset, value):
        return queryset.filter(
            Q(last_name__icontains=value) | Q(first_name__icontains=value) | Q(email__icontains=value)
        )

然后制作一般视图。

from django_filters.views import FilterView

from .filters import UserFilter

class AgentListView(ClassRequiredMixin, FilterView):

    filterset_class = UserFilter

有关您的模板,请参阅http://django-filter.readthedocs.org/en/latest/usage.html#the-template

答案 1 :(得分:0)

从1.x版本开始,MethodFilter was removed。现在看起来像:

import django_filters
from django.db.models import Q

from app.models import User

class UserFilter(django_filters.FilterSet):
    q = filters.CharFilter(method='filter_q')

    def filter_q(self, qs, name, value):
        return qs.filter(
            Q(last_name__icontains=value) | Q(first_name__icontains=value) | Q(email__icontains=value)
        )


并查看

from django_filters.views import FilterView

from .filters import UserFilter

class AgentListView(ClassRequiredMixin, FilterView):

    filterset_class = UserFilter

请注意,如果您使用的是DRF,则2.x中的filterset_class在1.x中被命名为filter_class

from django_filters import rest_framework as filters

class AgentListViewSet(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend, )
    filter_class = UserFilter

答案 2 :(得分:-2)

您可以使用Q() objects

来自文档:

Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

给出类似的东西:

SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')