【问题标题】:From Datefield get months in array in django qs从 Datefield 在 django qs 中获取月份数组
【发布时间】:2013-08-26 22:38:23
【问题描述】:

我有带 DateField 的 django 模型。 如果我需要从某个月份获取对象,我可以这样做:

objects = Model.objects.filter(date__month=8) 它工作正常,但如果我这样做:

objects = Model.objects.filter(date__month__in=[1, 2, 3])我收到错误:

FieldError at /
Join on field 'date' not permitted. Did you misspell 'month' for the lookup type?

有什么方法可以做我正在尝试的事情吗?

【问题讨论】:

    标签: django datetime django-queryset


    【解决方案1】:

    ORM __month 过滤器只进行精确匹配,但您可以将几个 Q 对象或在一起:

    objects = Model.objects.filter(Q(date__month=1) | Q(date__month=2) | Q(date__month=3))
    

    Q 对象使用标准 Python | 运算符,使用类的自定义 __or__ 方法实现,因此您可以使用 operator.or_reduce 从任意可迭代对象自动构建:

    list_of_months = [1, 5, 11]
    constraints = reduce(operator.or_, (Q(date__month=datenum) for datenum in list_of_months))
    objects = Model.objects.filter(constraints)
    

    【讨论】:

      【解决方案2】:

      您可以在filter() 中使用Q 对象,它们可用于使用| 的多个过滤条件。

      与时间相关的字段查找转换为基础字段类型的范围,因此 __in=[...] 不会自然地转换为基础 SQL IN (...),因此我们只能使用 oring Q 对象。

      【讨论】:

        猜你喜欢
        • 2013-08-27
        • 2019-02-09
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多