Skip to content

Instantly share code, notes, and snippets.

@leifdenby
Last active December 9, 2020 19:28
Show Gist options
  • Save leifdenby/4586e350586c014c1c9a to your computer and use it in GitHub Desktop.
Save leifdenby/4586e350586c014c1c9a to your computer and use it in GitHub Desktop.
Django function for loading fixtures which use the current migration state of the model
from django.core import serializers
import os
def loaddata(fixture_name, apps, ignorenonexistent=True):
"""
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`.
"""
# relative path to fixtures
fixtures_dir = 'fixtures'
# monkey patch serializers `apps` so that it uses the models in the current migration state
original_apps = serializers.python.apps
serializers.python.apps = apps
objects = None
for extension in ['json', 'yaml', 'xml']:
fixture_path = os.path.join(os.path.dirname(__file__), fixtures_dir, '%s.%s' % (fixture_name, extension))
if os.path.exists(fixture_path):
print "Loading fixtures from %s... " % fixture_path,
with open(fixture_path, 'rb') as f:
objects = serializers.deserialize(extension, f, ignorenonexistent=ignorenonexistent)
n = 0
for obj in objects:
obj.save()
n += 1
print "loaded %d objects." % n
serializers.python.apps = original_apps
if objects is None:
raise Exception("Couldn't find the '%s' fixture for the '%s' app." % (fixture_name, app_label))
@hwalinga
Copy link

hwalinga commented Dec 9, 2020

You can also make the call to loaddata directly. Don't need to replicate the code here. Just a django.core.management.call_command("loaddata", ignorenonexistent=ignorenonexistent) will do. Even if it reimports the serializers module, the monkeypatch is still there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment