Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created June 7, 2012 04:59
Show Gist options
  • Select an option

  • Save yuchant/2886688 to your computer and use it in GitHub Desktop.

Select an option

Save yuchant/2886688 to your computer and use it in GitHub Desktop.
Django: set database level defaults with postgresql_psycopg2 from the model file.
def db_default(field, db_default):
"""
Set attribute __db_default for signal to set default values with.
"""
if db_default == '':
db_default = "''"
field.__db_default = db_default
return field
class OrderShipLog(models.Model):
"""
This log will have read/write access from pg_endicia.
"""
date_created = db_default(models.DateTimeField(auto_now_add=True), 'false')
transaction_datetime = db_default(models.DateTimeField(blank=True, auto_now_add=True), 'now()')
# perfect example: auto_now_add only works from a django object, not any other SQL insert.
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()))
if not os.path.exists(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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment