Django日期过滤器按月份日期 [英] Django date filter by day of month

查看:118
本文介绍了Django日期过滤器按月份日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个查询,返回所有对象减去等于某个特定月份的某一天。这一年并不重要。在某个特定的日/月内获取对象很容易(假设 now = datetime.datetime.now()):

I need to write a query that returns all object less that or equal to a certain day of a certain month. The year is not important. It's easy enough to get an object by a particular day/month (assume 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中最好的方式是什么?

Seems that Django thinks I'm trying to do a join when combining multiple field lookups (publish_date__day__lte). What's the best way to do this in Django?

推荐答案

尝试这样:

选项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()函数:

Using extra() function:

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)。

It's assumed that you are using MySQL. For PostgreSQL, you need to change DAY(publish_date) and MONTH(publish_date) to DATE_PART('DAY', publish_date) and DATE_PART('MONTH', publish_date) respectively.

这篇关于Django日期过滤器按月份日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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