Login

Proper fixtures loading in south data migrations

Author:
JustDelight
Posted:
February 27, 2013
Language:
Python
Version:
1.4
Score:
1 (after 1 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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

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.