|
1 from django.core.management.base import BaseCommand, CommandError |
|
2 from django.core import serializers |
|
3 |
|
4 from optparse import make_option |
|
5 |
|
6 class Command(BaseCommand): |
|
7 option_list = BaseCommand.option_list + ( |
|
8 make_option('--format', default='json', dest='format', |
|
9 help='Specifies the output serialization format for fixtures.'), |
|
10 make_option('--indent', default=None, dest='indent', type='int', |
|
11 help='Specifies the indent level to use when pretty-printing output'), |
|
12 ) |
|
13 help = 'Output the contents of the database as a fixture of the given format.' |
|
14 args = '[appname ...]' |
|
15 |
|
16 def handle(self, *app_labels, **options): |
|
17 from django.db.models import get_app, get_apps, get_models |
|
18 |
|
19 format = options.get('format', 'json') |
|
20 indent = options.get('indent', None) |
|
21 show_traceback = options.get('traceback', False) |
|
22 |
|
23 if len(app_labels) == 0: |
|
24 app_list = get_apps() |
|
25 else: |
|
26 app_list = [get_app(app_label) for app_label in app_labels] |
|
27 |
|
28 # Check that the serialization format exists; this is a shortcut to |
|
29 # avoid collating all the objects and _then_ failing. |
|
30 if format not in serializers.get_public_serializer_formats(): |
|
31 raise CommandError("Unknown serialization format: %s" % format) |
|
32 |
|
33 try: |
|
34 serializers.get_serializer(format) |
|
35 except KeyError: |
|
36 raise CommandError("Unknown serialization format: %s" % format) |
|
37 |
|
38 objects = [] |
|
39 for app in app_list: |
|
40 for model in get_models(app): |
|
41 objects.extend(model._default_manager.all()) |
|
42 try: |
|
43 return serializers.serialize(format, objects, indent=indent) |
|
44 except Exception, e: |
|
45 if show_traceback: |
|
46 raise |
|
47 raise CommandError("Unable to serialize database: %s" % e) |