Django查询未知数量的多个日期范围 [英] Django query an unknown number of multiple date ranges

查看:109
本文介绍了Django查询未知数量的多个日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,允许用户选择多个年龄段的用户:18-24岁,25-34岁,35-44岁等。当前,如果用户选择了多个选择列表中的前两个字段,查询将返回用户18-34。如果用户选择18-24岁和35-44岁的用户,则该年龄段将包含18-44岁的所有年龄段,而不应包括25-34岁的用户。

I have a form which allows a user to select users by multiple age ranges: 18-24, 25-34, 35-44 etc. Currently if a user selects the first two fields in the multiple selection list, the query will return users 18 - 34. If a user selects 18 - 24 year olds, and 35-44 year olds, it will include all ages from 18 - 44, when it should not include users aged 25-34.

如何在查询中包括多个范围过滤器而又不知道在选择用户表单之前需要过滤的范围数?

How would you approach including multiple range filters on a query without knowing the number of ranges you need to filter by prior to the users form selections?

如果您知道用户要过滤的年龄范围的数量,我知道您可以使用Q链接范围查询。

If you knew the number of age ranges the user was going to filter by I know you could chain range queries using Q.

这是我当前的查询:

query = User.objects.filter(
            gender__in=genders,
            created__in=dates,
            data_source__in=sources,
            dob__range=[dob_from, dob_to]
        )

感谢adva

推荐答案

正如您在问题中所说,可以使用 Q()对象并将它们组合在一起。您不知道会有多少 Q()个对象,这不是问题。生成Q()对象的列表,然后将列表简化为单个 Q()

As you say in your question, you can use Q() objects and combine them together. It's not a problem that you don't know how many Q() objects there will be. Generate a list of the Q() objects, then reduce the list to a single Q().

from operator import or_

# import for Python 3, not required in Python 2
from functools import reduce

ranges = [(18,24), (35, 44)]  # hardcoded as an example, you can dynamically generate this
qs = [Q(dob_range=[dob_from_, dob_to]) for (dob_from_, dob_to) in ranges]
# combine the qs
dob_q = reduce(or_, qs, Q())

query = User.objects.filter(
    dob_q,
    gender__in=genders,
    created__in=dates,
    data_source__in=sources,
)

如果您不熟悉 reduce or _ ,则可以通过遍历列表获得相同的结果:

If you are unfamiliar with reduce and or_, you can get the same result by looping through the list:

qs = [Q(dob_range=[dob_from_, dob_to]) for (dob_from_, dob_to) in ranges]
dob_q = Q()
for q in qs:
    dob_q = dob_q | q

这篇关于Django查询未知数量的多个日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆