问题描述
我有一个MySQL数据库,除Django外,另一个应用程序正在使用该数据库.该应用程序使用'0000-00-00 00:00:00'
作为日期时间的默认值.
I have a MySQL database that is used by another application besides Django. That application uses '0000-00-00 00:00:00'
as default value for datetimes.
Django(v1.5.5)在读取数据库时将'0000-00-00 00:00:00'
日期时间解释为None
,而在写入数据库时将None
解释为NULL
.由于数据库将字段定义为NOT NULL
,因此将导致错误.
Django (v1.5.5) interprets '0000-00-00 00:00:00'
datetime as None
when reading the database and None
as NULL
when writing into the database. This causes an error since the database defines the field as NOT NULL
.
手动设置:
model.datetime = '0000-00-00 00:00:00'
不起作用,因为Django认为这是一个无效的日期.
Doesn't work because Django feels that this is an invalid date.
如何创建将None
插入为'0000-00-00 00:00:00'
的自定义日期时间字段?
How do I create a custom datetime field which inserts None
as '0000-00-00 00:00:00'
?
推荐答案
创建自定义DateTimeField
并覆盖get_db_prep_value
.该方法是从Django源复制粘贴的,并添加了一个用于处理None
的案例.该值应该以数据库特定的方式进行转换,这样虽然有点怪异,但是只要数据库接受0000-00-00 00:00:00
作为日期时间,它就可以工作.
Create a custom DateTimeField
and override the get_db_prep_value
. The method is copypasted from the django source and a case is added for handling None
. The value should be converted in a database specific manner so this is a bit hacky but it works as long as the database accepts 0000-00-00 00:00:00
as a datetime.
from django.db import models
class ZeroDateTimeField(models.DateTimeField):
def get_db_prep_value(self, value, connection, prepared=False):
# Casts datetimes into the format expected by the backend
if not prepared:
value = self.get_prep_value(value)
# Use zeroed datetime instead of NULL
if value is None:
return "0000-00-00 00:00:00"
else:
return connection.ops.value_to_db_datetime(value)
此答案是为Django 1.5编写的,尚未测试对其他版本的支持.
This answer was written for Django 1.5 and support with other versions has not been tested.
这篇关于Django ORM,将None datetime作为0插入MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!