Login

Proper fixtures loading in south data migrations

Author:
JustDelight
Posted:
February 27, 2013
Language:
Python
Version:
1.4
Tags:
fixtures migration fixture south datamigration
Score:
0 (after 0 ratings)

South documentation contains a description of the way you can load fixtures inside the data-migrations.

def forwards(self, orm): from django.core.management import call_command call_command("loaddata", "my_fixture.json")

It seems pretty clear and easy, but in fact it does not work the way you expect from south migrations, because the fixture loading does not engage the orm object. So, it allows loaddata management command to use standard models loading mechanism, and it would provide the most recent version of the models, obviously, which may not correspond to the schema of the fixture`s data. To be ensured that migration will use appropriate version of the models for fixture loading you could use code like follows:

class Migration(DataMigration):

    def forwards(self, orm):
        load_fixture('my_fixture.json', orm)

class Migration(DataMigration):

    def forwards(self, orm):
        with southern_models(orm):
            call_command("loaddata", "my_fixture.json")
 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
27
28
29
30
31
32
33
34
from django.db import models
from django.core.management import call_command

def load_fixture(file_name, orm):
    original_get_model = models.get_model
    
    def get_model_southern_style(*args):
        try:
            return orm['.'.join(args)]
        except:
            return original_get_model(*args)
    
    models.get_model = get_model_southern_style
    
    call_command('loaddata', file_name)
    
    models.get_model = original_get_model

# or use it via context manager
from contextlib import contextmanager

@contextmanager
def southern_models(orm):
    original_get_model = models.get_model

    def get_model_southern_style(*args):
        try:
            return orm['.'.join(args)]
        except:
            return original_get_model(*args)

    models.get_model = get_model_southern_style
    yield
    models.get_model = original_get_model

More like this

  1. Loading initial data per model at table creation (useful with migrations) by GigiusB 8 months, 2 weeks ago
  2. dumpdata/loaddata with MySQL and ForeignKeys by cmgreen 7 years, 2 months ago
  3. dumpdata/loaddata with MySQL and ForeignKeys (Revision 2) by cmgreen 7 years ago
  4. dumpdata/loaddata with MySQL and ForeignKeys, as django command by brondsem 5 years, 11 months ago
  5. Auto-rename duplicate fields by christian.oudard 5 years, 7 months ago

Comments

onefourtwoeightfiveseven (on June 17, 2014):

On line 5 'models.get_mode' should be 'models.get_model'. Other than that, it worked great.

#

JustDelight (on July 14, 2014):

Fixed it. Thank you.

#

Please login first before commenting.