繁体   English   中英

Django - 根据前端用户提供的信息进行查询。 并非每次都会使用所有过滤器。 如何做到这一点?

[英]Django - Make query based on information provided from a user on front end. Not all filters will be used every time. How to achieve this?

我有个问题。 我正在构建一个应用程序,用户可以在表单中使用 select 一些过滤选项。 并非每次都会使用所有选项。 我不知道如何构建正确的 Django 查询。

起初我尝试了这种方法:

if mileage:
    if mileage_less_more == 'mileage_less_than':
        cars = cars.objects.filter(price__lte=mileage)
    if mileage_less_more == 'mileage_more_than':
        cars = cars.objects.filter(price__gte=mileage)

if production_year:
    if production_year_less_more == 'production_year_less_than':
        cars = cars.objects.filter(production_year__lte=production_year)
    if production_year_less_more == 'production_year_more_than':
        cars = cars.objects.filter(production_year__gte=production_year)
    if production_year_less_more == 'production_year_exact':
        cars = cars.objects.filter(production_year=production_year)

我假设它会像 python 中的任何其他变量一样工作,即使不使用上述过滤器之一(例如,里程为无),它也不会执行。 但是据我所知,Django 不支持这种方法。

然后我用 f 字符串尝试了许多奇怪的东西,但它也没有用。

然后我尝试了这种方法:

if mileage:
    if mileage_less_more == 'mileage_less_than':
        mileage_qs = Car.objects.filter(price__lte=mileage)
    if mileage_less_more == 'mileage_more_than':
        mileage_qs = Car.objects.filter(price__gte=mileage)
else:
    mileage_qs = Car.objects.all()

if production_year:
    if production_year_less_more == 'production_year_less_than':
        production_year_qs = Car.objects.filter(production_year__lte=production_year)
    if production_year_less_more == 'production_year_more_than':
        production_year_qs = Car.objects.filter(production_year__gte=production_year)
    if production_year_less_more == 'production_year_exact':
        production_year_qs = Car.objects.filter(production_year=production_year)
else:
    production_year_qs = Car.objects.all()

cars_final = Car.objects.all().intersection( mileage_qs, production_year_qs)

它有效。 但它会在以后引起问题。 我需要对这个cars_final项目进行更多过滤。 并且 Django 也不支持相交后的过滤。

我可以稍后在我的代码中尝试粘贴整个cars_final ,然后在intersection()应用额外的filter()之前,它会很快变得非常混乱。

我确信有更优雅的方法可以做到这一点,但我只是不知道怎么做,而且我无法用谷歌搜索它。 有人可以帮我吗?

您应该查看https://django-filter.readthedocs.io/en/stable/ 它拥有您在过滤方面所需的一切,并且易于设置。 尝试创建自己的过滤器比人们想象的要复杂。

如果您真的想创建自己的过滤器,您可以使用关键字 arguments 来构建您的查询字典,然后再将其传递给您的查询集。 像这样的东西:

data = {}

if variable == 1:
    data['key'] = 'foo'
elif variable == 2:
    data['key_2'] = 'bar'

if data:
    MyModel.objects.filter(**data)
else:
    MyModel.objects.all()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM