0

My django application needs data to work properly, so in certain migration I loaded data using the recommended method by almost all stack overflow answers:

    from django.core.management import call_command

    def load_fixture(apps, schema_editor):
        call_command('loaddata', 'fixture_name', app_label='my_app')

    class Migration(migrations.Migration):

        ...

        operations = [
            migrations.RunPython(load_fixture),
        ]

In the following migration, I deleted a field and added another field. So far so good.

Now I want to test my application, but when the test database is being created, the 'call_command' above fails because the fixtures don't specify values for the field created in the next migration. I suspect this is because call_command isn't loading the objects on the test database but on settings.DATABASES['default'].

How should I load fixtures in a migration so that I can build test databases?

djvg
  • 11,722
  • 5
  • 72
  • 103
Marco Lavagnino
  • 1,140
  • 12
  • 31

1 Answers1

0

For tests, I know you can load in fixtures within Djangos TestCase, see django docs

For production, The approach you are taking using loaddata seems viable, but you would need to make sure your fixtures are kept up to date (as youve highlighted), as fixture inserting is quite forceful, an alternative is to create your models using the ORM inside of a RunPython operation, this can help to give them more flexibility..

There is a feature request in Django for something more official, though I'm not sure if its being considered or not, but it would only add convenience for fixture loading, not a way to make fixtures dynamic..

this other stack overflow post contains some other interesting approaches

Hope that's in some way helpful

Community
  • 1
  • 1
farridav
  • 933
  • 8
  • 18