好的,在运行函数测试时遇到了奇怪的时区问题。使用Django 1.4和Python 2.7。在MySQL上,DateTimeField()中的毫秒会被截断吗?这是我唯一的理论。
模型文件
from django.db import models
from django.utils import timezone
class Search(models.Model):
query = models.CharField(max_length=200, null=True)
query_date = models.DateTimeField(null=True)
test.py
from django.test import TestCase
from django.utils import timezone
from search.models import Search
class SearchModelTest(TestCase):
def test_creating_a_new_search_and_saving_it_to_the_database(self):
# start by creating a new Poll object with its "question" set
search = Search()
search.query = "Test"
search.query_date = timezone.now()
# check we can save it to the database
search.save()
# now check we can find it in the database again
all_search_in_database = Search.objects.all()
self.assertEquals(len(all_search_in_database), 1)
only_search_in_database = all_search_in_database[0]
self.assertEquals(only_search_in_database, search)
# and check that it's saved its two attributes: question and pub_date
self.assertEquals(only_search_in_database.query, "Test")
self.assertEquals(only_search_in_database.query_date, search.query_date)
测试以以下方式失败:
self.assertEquals(only_search_in_database.query_date, search.query_date)
AssertionError: datetime.datetime(2013, 1, 16, 21, 12, 35, tzinfo=<UTC>) != datetime.datetime(2013, 1, 16, 21, 12, 35, 234108, tzinfo=<UTC>)
我认为现在发生的是毫秒数在保存到数据库后被截断了。这种情况是否可能?我使用的是MySQL v5.5,请问是MySQL自身截取了日期吗?