Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

python - DateTimeField queryset returning None in Django

I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB.

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)

The field in the DB:

date DATETIME

The tuples are populated in the database and running SQL queries directly on the DB is working perfectly.

This is the queryset I am currently using in Django:

queryset = ChangeMetrics.objects.filter(~Q(changed=None), ~Q(date=None), ~Q(version_id=None))

I have tried a raw query and also a version of the query that uses exclude(), but that still returns None for date.

I am accessing the entries in the queryset through a for loop and simply accessing date through entry.date inside the for loop.

Edit: 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

not sure if you were able to figure this out, but I just had this problem and was able to fix it.

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

After running that if fixed my issue. Maybe in your case you could try modifying to datetime(6) instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...