Django dumpdata writes datetimes as nulls
我有一个包含我的模型的Django数据库(sqlite)。 特别是,有一个模型的日期字段在数据库中不为null(通过sqlite shell确认),dumpdata始终序列化为null。
我正在python 2.7.5下使用Django 1.4.5。
真正奇怪的部分是,并非所有日期字段都执行此操作。 这似乎是数据库中唯一键入为
我的问题是:是什么原因造成的,我该如何制止它? 或者,什么是dumpdata的好选择?
这是模型代码:
1 2 3 4 5 6 7 8 9 10 | class AccountTransaction(models.Model): value = models.FloatField() description = models.CharField(max_length = 1000) credit_in = models.ForeignKey(Organisation, on_delete = models.PROTECT, related_name='credits_in') debit_in = models.ForeignKey(Organisation, on_delete = models.PROTECT, related_name='debits_in') date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'date' |
这是模式:
1 2 3 4 5 6 7 | CREATE TABLE"mainapp_accounttransaction" ("credit_in_id" integer, "description" varchar(1000), "date" datetime NOT NULL DEFAULT '2012-06-18', "debit_in_id" integer, "id" integer PRIMARY KEY, "value" real); |
这是一个实例,该实例未正确序列化为空日期:
1 2 3 4 5 6 7 8 9 10 11 | { "pk": 1, "model":"mainapp.accounttransaction", "fields": { "debit_in": 1, "date": null, "credit_in": 1, "description":"Charge for standard of Example5-1 limited (order Incorporation Order no. 13 for Example5-1 limited (UK Company temporary number: UN177efa40-2022-11e1-b383-e89a8f7f9c14))", "value": 100.0 } } |
为了进行比较,以下是在数据库中查找结果:
1 2 | sqlite> select * from mainapp_accounttransaction where id is 1; 1|Charge for standard of Example5-1 limited (order Incorporation Order no. 13 for Example5-1 limited (UK Company temporary number: UN177efa40-2022-11e1-b383-e89a8f7f9c14))|2012-06-18|1|1|100.0 |
更新:这是一个有趣的事情:
1 2 3 4 | >>> import mainapp.models >>> ats = mainapp.models.AccountTransaction.objects.all() >>> [o.date for o in ats] [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None] |
事实证明,sqlite处理奇怪的默认值。 使用
解决方案是通过ORM为每个对象设置值。