gpt4 book ai didi

python - Django-过滤多个URL参数

转载 作者:太空狗 更新时间:2023-10-29 23:55:00 31 4
gpt4 key购买 nike

我正在使用 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

模型.py:

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

也许我做错了什么?

最佳答案

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

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?

关于python - Django-过滤多个URL参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203259/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com