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.

相关文章