Django过滤多个URL参数

时间:2014-08-08 12:12:54

标签: python django django-filter

我正在使用Django-filter应用在我的网站上构建搜索。这是代码:

class PropertyFilter(django_filters.FilterSet):
city = django_filters.ModelMultipleChoiceFilter(queryset=City.objects.all(), widget = CheckboxSelectMultiple)
trade_type = django_filters.ModelMultipleChoiceFilter(queryset=Trade.objects.all(), widget = CheckboxSelectMultiple)

class Meta:
    model = Property
    fields = ['city', 'trade_type']

问题在于,当用户标记两个城市时,Django-filter仅通过最后一个URL参数(此库中的城市编号2)过滤对象:

http://example.org/lt/list/city=1&city=2

Models.py

class City(models.Model):
    name = models.CharField(max_length=250, verbose_name=_('Name'))

也许我做错了什么?

3 个答案:

答案 0 :(得分:4)

您可以创建查询字符串的复数形式,并接受列表作为过滤器参数:

http://example.org/lt/list/?cities=1,2


class CustomFilterList(django_filters.Filter):
    def filter(self, qs, value):
        if value not in (None, ''):
            values = [v for v in value.split(',')]
            return qs.filter(**{'%s__%s' % (self.name, self.lookup_type): values})
        return qs

class PropertyFilter(django_filters.FilterSet):
    city = django_filters.ModelMultipleChoiceFilter(queryset=City.objects.all(), widget = CheckboxSelectMultiple)
    trade_type = django_filters.ModelMultipleChoiceFilter(queryset=Trade.objects.all(), widget = CheckboxSelectMultiple)
    cities = CustomFilterList(name="city", lookup_type="in")

    class Meta:
        model = Property
        fields = ['cities', 'city', 'trade_type']

请查看此答案,以便正确过滤值列表:

  

Possible to do an `in` `lookup_type` through the django-filter URL parser?

答案 1 :(得分:1)

您可以使用您尝试的相同网址来使用它。按照我的例子。您必须传递要过滤的选项。

我打电话的网址:

http://example.org/product-list/gender=1&gender=2

filters.py

GENDER_CHOICES = tuple(
    ProductAttributeOptions.objects.filter(group__name='gender').values_list('id', 'option'))

class ProductFilter(django_filters.FilterSet):        
    gender = django_filters.MultipleChoiceFilter(choices=GENDER_CHOICES,
                                                 method='filter_gender')

    def filter_gender(self, qs, name, value):
        result = qs.filter(Q(attribute_values__attribute__name='gender',
                         attribute_values__value_option__in=value))

        return result

class Meta:
    model = Product
    fields = ('gender')

希望这可以提供帮助。我从official docs获得了灵感。

答案 2 :(得分:1)

最好的方法是使用来自 Django filter DOC 的自定义过滤器 在我的情况下,我使用 (',') 来拆分 url 应如下所示:

<块引用>

localhost:8000/?city=1,2,3(你可以使用字符串值)

    
   class F(django_filters.FilterSet):
         city = CharFilter(method='my_custom_filter')

         class Meta:
            model = Property
            fields = ['city','trade_type']

         def my_custom_filter(self, queryset, name, value):
            value_list = value.split(u',') #split the values by ,
            return queryset.filter(**{
            name+"__in": value_list, #add __in to get each value of the list
            })