Login

post_migrate handler to load initial SQL after migrating with south

Author:
stingydrone
Posted:
January 6, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

I found that South doesn't execute initial sql file after a migration, like what Django can do after syncdb. So here's the workaround by using post_migrate signal.

Usage: Put your SQL files the same way as you would if you were to use Django to load your initial SQL file (follow Django doc). The only difference is that, the SQL filename needs to in this format: <app_label>.sql OR <app_label>.<backend>.sql This is done this way since the migration is run per app.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months 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?

#

Please login first before commenting.