Skip to content

Instantly share code, notes, and snippets.

@RobertoMaurizzi
Forked from danni/migration_loaddata.py
Created November 16, 2023 08:28
Show Gist options
  • Save RobertoMaurizzi/5e0678b239989b519bfd909e3cf2bc41 to your computer and use it in GitHub Desktop.
Save RobertoMaurizzi/5e0678b239989b519bfd909e3cf2bc41 to your computer and use it in GitHub Desktop.
Django function for loading fixtures which use the current migration state of the model
import os
import logging
from django.core import serializers
LOGGER = logging.getLogger(__name__)
def load_fixture(app, fixture, ignorenonexistent=True):
"""
A factory to load a named fixture via a data migration.
"""
def inner(apps, schema_editor):
"""
Loads migrations that work at current state of a model, in constrast to
`loaddata` which requires a fixture to have data matching the fields
defined in `models.py`.
Based on https://gist.github.com/leifdenby/4586e350586c014c1c9a
"""
# relative path to fixtures
fixtures_dir = os.path.join(app, 'fixtures')
# monkey patch serializers `apps` so that it uses the models in the
# current migration state
original_apps = serializers.python.apps
try:
serializers.python.apps = apps
objects = None
for extension in ('json', 'yaml', 'xml'):
fixture_path = os.path.join(
fixtures_dir,
'%s.%s' % (fixture, extension))
LOGGER.debug("Trying %s", fixtures_dir)
if os.path.exists(fixture_path):
print("Loading fixtures from %s... " % fixture_path)
with open(fixture_path, 'rb') as file_:
objects = serializers.deserialize(
extension, file_,
ignorenonexistent=ignorenonexistent)
count = 0
for obj in objects:
obj.save()
count += 1
print("Loaded %d objects." % count)
if objects is None:
raise Exception(
"Couldn't find the '%s' fixture for the '%s' app." % (
fixture, app))
finally:
serializers.python.apps = original_apps
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment