Login

Loading initial data per model at table creation (useful with migrations)

Author:
GigiusB
Posted:
July 12, 2014
Language:
Python
Version:
1.4
Tags:
loaddata migration south
Score:
0 (after 0 ratings)

A very simple way of automatically loading data on model creation.

As I am using South I wanted an automatic way of loading initial data only when a new model is create during a migration. Django provides almost everything out of the box by providing the post_syncdb signal (triggered also by South migrate command) and the loaddata command.

The code will simply look for a an existing fixture named <model>_initial.* and invoke the loaddata command to try to load it

Note: beware post_syncdb signal is deprecated since version 1.7: it has been replaced by post_migrate.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import glob
from django.core.management import call_command
from django.db.models.signals import post_syncdb
import os

def fixtures_loading(sender, app, *args, **kwargs):
    created_models = kwargs.get('created_models', [])
    for model in created_models:
        pth = '%s/fixtures/%s_initial.*' % (os.path.dirname(app.__file__), model.__name__ )
        fixtures = glob.glob( pth )
        if fixtures:
            print "Found initial fixtures for %s fixtures:" % model.__name__, fixtures
            call_command('loaddata', '%s_initial' % model.__name__)

post_syncdb.connect(fixtures_loading)

More like this

  1. Proper fixtures loading in south data migrations by JustDelight 2 years, 1 month ago
  2. immitating 'real' post_syncdb signal by jango 5 years ago
  3. post_migrate handler to load initial SQL after migrating with south by stingydrone 4 years, 3 months ago
  4. Post-post-syncdb and post-post-migrate by theY4Kman 1 week, 4 days ago
  5. Export models as json by aconbere 8 years, 1 month ago

Comments

Please login first before commenting.