Skip to content

Instantly share code, notes, and snippets.

@halfnibble
Created August 30, 2016 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halfnibble/d5abcbcd2aa21bfc13e5348d250fb8cf to your computer and use it in GitHub Desktop.
Save halfnibble/d5abcbcd2aa21bfc13e5348d250fb8cf to your computer and use it in GitHub Desktop.
Django Management Command to Create Clean Fixtures
# Place in /installed_app/management/commands/cleandump.py
import os
from django.core import management
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Creates clean dumpdata fixtures.'
def add_arguments(self, parser):
# Positional args
parser.add_argument('app_name', type=str)
# Named (optional) arguments
parser.add_argument('--dest', dest='dest',
help=('Destination of dump file. Default: '+
'<app>/fixtures/<app>_testdata.json'))
def handle(self, *args, **options):
app_name = options['app_name']
if options['dest']:
dest = options['dest']
else:
dest = '{0}/fixtures/{0}_testdata.json'.format(app_name)
dest_dir = os.path.dirname(dest)
if os.path.exists(dest_dir):
self.stdout.write('Path exists: {}'.format(dest_dir))
else:
self.stdout.write('Mkdir: {}'.format(dest_dir))
os.makedirs(dest_dir)
self.stdout.write('Creating dumpdata of {}'.format(app_name))
management.call_command('dumpdata', app_name, '--exclude=sessions',
'--exclude=admin', '--exclude=contenttypes',
'--exclude=auth.Permission', natural_foreign=True, indent=4,
output=dest)
@halfnibble
Copy link
Author

Usage

If you have an app named posts and you want the dumpdata in posts/fixtures/posts_testdata.json, then simply run:

./manage.py cleandump posts

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