gpt4 book ai didi

python - Django TruncDate 给出空值

转载 作者:行者123 更新时间:2023-12-02 16:44:47 25 4
gpt4 key购买 nike

我正在使用 Django 2.2

我正在使用 Django 查询过滤记录

from datetime import datetime
from django.db.models.functions import TruncDate

start_date = datetime.strptime('2020-02-01', '%Y-%m-%d').date()
end_date = datetime.strptime('2020-03-31', '%Y-%m-%d').date()

lead_list = LeadList.objects.all()

# Filter query
query = LeadListEntry.objects.filter(
lead_list__in=lead_list
)

# Filter by start date
query = query.filter(
created__gte=start_date
)

# Filter by end date
query = query.filter(
created__lte=end_date
)

# Annotate date
query = query.annotate(
created_date=TruncDate('created')
).order_by(
'created_date'
).values('created_date').annotate(
**{'total': Count('created')}
)

生成的SQL查询是

SELECT 
DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC')) AS `created_date`,
COUNT(`lead_generation_leadlistentry`.`created`) AS `total`
FROM `lead_generation_leadlistentry`
WHERE (
`lead_generation_leadlistentry`.`lead_list_id` IN (
SELECT
U0.`id` FROM `lead_generation_leadlist` U0
WHERE
U0.`deleted` IS NULL
)
AND `lead_generation_leadlistentry`.`created` >= '2020-02-01 00:00:00'
AND `lead_generation_leadlistentry`.`created` <= '2020-03-31 00:00:00'
)
GROUP BY DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC'))
ORDER BY `created_date` ASC

这在本地和暂存服务器上表现不同

本地开发服务器

+--------------+-------+
| created_date | total |
| ------------ | ----- |
| 2020-02-25 | 15 |
| 2020-02-27 | 10 |
+--------------+-------+

暂存服务器

+--------------+-------+
| created_date | total |
| ------------ | ----- |
| null | 15 |
+--------------+-------+

日期列为null

注意:Django 已通过 USE_TZ=True

启用时区

LeadListEntry 模型

class LeadListEntry(models.Model):
lead_list = models.ForeignKey(LeadList, on_delete=models.CASCADE, related_name='lead_list_entry')
data = models.TextField(help_text='Lead List entry data. (JSON data)', blank=False)

created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

最佳答案

这是用户遇到相同错误的解决方案

错误不在于 Django,而在于 MySQL 数据库设置。

日期字段返回 null 因为 CONVERT_TZ 不起作用。这可能是因为 MySQL 数据库中没有时区数据。

要导入时区数据,执行以下命令

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

导入完成后,重启mysql服务器。

关于python - Django TruncDate 给出空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810946/

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