我尝试过,post_syncdb
但使用 .sql 文件为时已晚。挂钩class_prepared
及时解决了,syncdb
但我意识到我把事情复杂化了。我不妨在模型实例化时运行一些代码。
当我需要再次摆弄这个时,我最终得到了一个可以在 6 个月内轻松理解的直截了当的解决方案。
def db_default(field, db_default):
"""
Set attribute __db_default for signal to set default values with.
"""
field.__db_default = db_default
return field
class OrderShipLog(models.Model):
date = db_default(models.DateTimeField(), 'now()')
def generate_default_sql(model):
"""
Generate SQL for postgresql_psycopg2 default values because the shipping
database post doesn't guarantee posting certain fields but id like them all to be strings.
"""
db_fields = filter(lambda x: hasattr(x, '__db_default'), model._meta.fields)
db_table = model._meta.db_table
modelname = model._meta.object_name
sql_dir = os.path.join(os.path.dirname(__file__), 'sql/')
sql_filename = os.path.join(sql_dir, '{modelname}.postgresql_psycopg2.sql'.format(
modelname=modelname.lower()))
from django.db import connection
if not db_table in connection.introspection.table_names():
print >> sys.stderr, "{0} not in introspected table list; creating db default sql file : {1}".format(db_table, sql_filename)
try:
if not os.path.exists(sql_dir):
os.makedirs(sql_dir)
with open(sql_filename, 'w+') as f:
for field in db_fields:
attname, db_column = field.get_attname_column()
if not field.__db_default:
raise Exception("Must enter value for field {modelname}.{field}.__db_default".format(
modelname=modelname,
field=attname))
f.write('ALTER TABLE {db_table} ALTER COLUMN {db_column} SET DEFAULT {default};\n'.format(
db_table=db_table,
db_column=db_column,
default=field.__db_default,
))
except Exception, e:
print >> sys.stderr, "Could not generate SQL file. Manually set the defaults! {0}\n".format(e) * 10
generate_default_sql(OrderShipLog)