DateTimeField queryset returning None in Django(DateTimeField 查询集在 Django 中返回 None)
问题描述
我正在尝试创建一个查询集,用于获取数据库中 DATETIME 的 DateTimeField 的值.
I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB.
models.py 中的类:
The class in models.py:
class ChangeMetrics(models.Model):
id = models.IntegerField(primary_key=True)
file_id = models.ForeignKey(File, db_column = 'file_id')
version_id = models.ForeignKey(Version, db_column = 'version_id')
function_id = models.ForeignKey(Function, blank=True, db_column = 'function_id')
date = models.DateTimeField(blank=True, null=True)
user = models.TextField(blank=True)
changed = models.IntegerField(blank=True, null=True)
数据库中的字段:
date DATETIME
元组填充在数据库中,直接在数据库上运行 SQL 查询运行良好.
The tuples are populated in the database and running SQL queries directly on the DB is working perfectly.
这是我目前在 Django 中使用的查询集:
This is the queryset I am currently using in Django:
queryset = ChangeMetrics.objects.filter(~Q(changed=None), ~Q(date=None), ~Q(version_id=None))
我尝试了一个原始查询和一个使用 exclude() 的查询版本,但仍然返回 None 日期.
I have tried a raw query and also a version of the query that uses exclude(), but that still returns None for date.
我正在通过 for 循环访问查询集中的条目,并通过 for 循环内的 entry.date 简单地访问日期.
I am accessing the entries in the queryset through a for loop and simply accessing date through entry.date inside the for loop.
Django 1.6.5 版我也尝试通过 Django shell 获取值,但没有成功.
Django version 1.6.5 I have also tried getting the values through the Django shell, to no success.
有什么可能出问题的想法吗?
Any ideas on what could be wrong?
推荐答案
不确定你是否能够解决这个问题,但我刚刚遇到了这个问题并且能够解决它.
not sure if you were able to figure this out, but I just had this problem and was able to fix it.
因此,Django 迁移将 DB 中的列创建为 datetime(6) 而不是 datetime.这导致 Django 模型无法实例化 Datetime 对象.
So, Django migrations were creating the column in the DB as datetime(6) instead of datetime. This was causing the Django models to fail to instantiate the Datetime object.
ALTER TABLE `my_table`
MODIFY COLUMN `created` datetime NOT NULL
运行后,如果解决了我的问题.也许在您的情况下,您可以尝试修改为 datetime(6) .
After running that if fixed my issue. Maybe in your case you could try modifying to datetime(6) instead.
这篇关于DateTimeField 查询集在 Django 中返回 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:DateTimeField 查询集在 Django 中返回 None


基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01