I tried doing post_syncdb
but it was too late to use .sql files. Hooking into class_prepared
worked out in time for syncdb
but I realized I was overcomplicating things. I might as well run some code once at model instantiation.
I ended up with a straight forward solution that can be easily understood in 6 months when I need to fiddle with this again.
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)