Django日期过滤器按日期过滤

时间:2009-11-03 00:58:35

标签: python django

我需要编写一个查询,返回所有对象少于或等于特定月份的某一天。这一年并不重要。在特定的日/月(假设为now = datetime.datetime.now()):

时,可以轻松获取对象
posts = TodaysObject.objects.filter(publish_date__day=now.day, publish_date__month=now.month)

但我不能这样做:

posts = TodaysObject.objects.filter(publish_date__day__lte=now.day, publish_date__month=now.month)

似乎Django认为我在组合多个字段查找时尝试进行连接(publish_date__day__lte)。在Django中最好的方法是什么?

3 个答案:

答案 0 :(得分:7)

试试这个:

选项1:

from django.db.models import Q

datafilter = Q()
for i in xrange(1, now.day+1):
    datafilter = datafilter | Q(publish_date__day=i)
datafilter = datafilter & Q(publish_date__month=now.month)
posts = TodaysObject.objects.filter(datafilter)

选项2:

执行原始SQL查询:

def query_dicts(query_string, *query_args):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(query_string, query_args)
    col_names = [desc[0] for desc in cursor.description]
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        row_dict = dict(izip(col_names, row))
        yield row_dict
    return
posts = query_dicts('SELECT * FROM tablename WHERE DAY(publish_date)<=%s AND MONTH(publish_date)=%s', now.day, now.month)

使用extra()函数:

posts = TodaysObject.objects.extra([where='DAY(publish_date)<=%d AND MONTH(publish_date)=%d' % (now.day, now.month)])

假设您正在使用MySQL。对于PostgreSQL,您需要分别将DAY(publish_date)和MONTH(publish_date)更改为DATE_PART('DAY',publish_date)和DATE_PART('MONTH',publish_date)。

答案 1 :(得分:1)

它并不总是可以从一个数据库引擎移植到另一个数据库引擎,但您可能需要查看extra() queryset方法。

from django docs

这允许您注入原始sql来构造比django queryset api更复杂的查询。

如果您的应用程序需要可移植到不同的数据库引擎,您可以尝试重组,以便您有日,月和年整数字段。

答案 2 :(得分:0)

now = datetime.date.today()
post = TodaysObject.objects.raw("SELECT * FROM (app_name)_todaysobject WHERE DAY(publish_date) =%(day)d AND MONTH(publish_date)=%(month)d" %{'day' : today.day, 'month':today.month} )