DateTimeField queryset在Django中返回None [英] DateTimeField queryset returning None in Django
问题描述
我正在尝试创建一个查询器来获取数据库中DATETIME的DateTimeField的值。
I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB.
model.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)
DB中的字段:
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.
任何想法可能是错的?
推荐答案
不确定如果你能够弄清楚这一点,但我刚刚遇到这个问题,并能够解决它。
not sure if you were able to figure this out, but I just had this problem and was able to fix it.
所以,Django迁移在数据库中创建列为datetime(6)而不是datetime。这导致Django模型无法实例化日期时间对象。
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 queryset在Django中返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!