post_migrate handler to load initial SQL after migrating with south

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def run_initial_sql(sender, **kwargs):
    app_label = kwargs.get('app')
    import os
    from django.db import connection, transaction
    app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(app_label).__file__), 'sql'))
    backend_name = connection.settings_dict['ENGINE'].split('.')[-1]
    sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)),
                 os.path.join(app_dir, "%s.sql" % app_label)]
    cursor = connection.cursor()
    for sql_file in sql_files:
        try:
            if os.path.exists(sql_file):
                print "Loading initial SQL data from '%s'" % sql_file
                f = open(sql_file)
                sql = f.read()
                f.close()
                cursor.execute(sql)
        except Exception, e:
            sys.stderr.write("Failed to install custom SQL file '%s': %s\n" % \
                                (sql_file, e))
            import traceback
            traceback.print_exc()
            transaction.rollback_unless_managed()
        else:
            transaction.commit_unless_managed()
post_migrate.connect(run_initial_sql)                                                                   

More like this

  1. immitating 'real' post_syncdb signal by jango 3 years, 2 months ago
  2. Load customized SQL by roppert 4 years, 3 months ago
  3. Create permissions for proxy models by charettes 1 year, 4 months ago
  4. caching parsed templates by forgems 5 years, 6 months ago
  5. decorator to add GUID Field to Django Models by trubliphone 4 months, 2 weeks ago

Comments

mmoya (on January 25, 2011):

Hi,

Before south.. i use a lot of sql files in the form sql/modelname.sql

Now, i need tu put only one file with all the sql statements? Thay is, only one file appname.sql whit the content of the old modelname.sql files?

#

(Forgotten your password?)