Created
August 30, 2016 05:27
-
-
Save halfnibble/d5abcbcd2aa21bfc13e5348d250fb8cf to your computer and use it in GitHub Desktop.
Django Management Command to Create Clean Fixtures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
If you have an app named
posts
and you want the dumpdata inposts/fixtures/posts_testdata.json
, then simply run:./manage.py cleandump posts