gpt4 book ai didi

python - Django 日期按月份过滤

转载 作者:太空狗 更新时间:2023-10-30 02:14:25 24 4
gpt4 key购买 nike

我需要编写一个查询,返回小于或等于某个月某天的所有对象。年份并不重要。获取特定日期/月份的对象非常容易(假设 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 中执行此操作的最佳方法是什么?

最佳答案

试试这个:

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

关于python - Django 日期按月份过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com