3

What methods do you use to set up database level defaults in django?

I understand this is a django wontfix decision, but there must be some ideas floating around about a way to implement this if written for a specific backend (postgres).

I'd like to power this through python so I'd prefer not to use /sql/.sql files.

I was thinking I might set attributes on existing fields such as:

foo = models.CharField(max_length=256, blank=True)
foo.db_default = ''

Then filter through fields and construct an ALTER COLUMN SET DEFAULT query.

Where would I put that though? The docs say not to alter the database in the post_syncdb hook.

Any ideas where to put this action? I'm also thinking I could generate the sql/.sql files dynamically. A management command would be better than nothing. Automatic would be great. Hmm I wonder if post_syncdb can generate sql files in time to be executed? Will test.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.