Ticket #12775: django-12775.diff

File django-12775.diff, 11.2 KB (added by Joshua Ginsberg <jag@…>, 14 years ago)

Add exclude model support, unit tests, update docs

  • django/core/management/commands/dumpdata.py

    ### Eclipse Workspace Patch 1.0
    #P django-trunk
     
    1616            default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load '
    1717                'fixtures into. Defaults to the "default" database.'),
    1818        make_option('-e', '--exclude', dest='exclude',action='append', default=[],
    19             help='App to exclude (use multiple --exclude to exclude multiple apps).'),
     19            help='An appname or appname.ModelName to exclude (use multiple --exclude to exclude multiple apps/models).'),
    2020        make_option('-n', '--natural', action='store_true', dest='use_natural_keys', default=False,
    2121            help='Use natural keys if they are available.'),
    2222    )
     
    3030        indent = options.get('indent',None)
    3131        using = options.get('database', DEFAULT_DB_ALIAS)
    3232        connection = connections[using]
    33         exclude = options.get('exclude',[])
     33        excludes = options.get('exclude',[])
    3434        show_traceback = options.get('traceback', False)
    3535        use_natural_keys = options.get('use_natural_keys', False)
    3636
    37         excluded_apps = set(get_app(app_label) for app_label in exclude)
     37        excluded_objs = set()
     38        for exclude in excludes:
     39            if '.' in exclude:
     40                app_label, model_name = exclude.split('.', 1)
     41                model_obj = get_model(app_label, model_name)
     42                if not model_obj:
     43                    raise CommandError('Unknown model in excludes: %s' % exclude)
     44                excluded_objs.add(model_obj)
     45            else:
     46                try:
     47                    app_obj = get_app(exclude)
     48                except ImproperlyConfigured:
     49                    raise CommandError('Unknown app in excludes: %s' % exclude)
     50                else:
     51                    excluded_objs.add(app_obj)
    3852
    3953        if len(app_labels) == 0:
    40             app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_apps)
     54            app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_objs)
    4155        else:
    4256            app_list = SortedDict()
    4357            for label in app_labels:
     
    4761                        app = get_app(app_label)
    4862                    except ImproperlyConfigured:
    4963                        raise CommandError("Unknown application: %s" % app_label)
    50 
     64                    if app in excluded_objs:
     65                        continue
    5166                    model = get_model(app_label, model_label)
    5267                    if model is None:
    5368                        raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
     
    6479                        app = get_app(app_label)
    6580                    except ImproperlyConfigured:
    6681                        raise CommandError("Unknown application: %s" % app_label)
     82                    if app in excluded_objs:
     83                        continue
    6784                    app_list[app] = None
    6885
    6986        # Check that the serialization format exists; this is a shortcut to
     
    7996        # Now collate the objects to be serialized.
    8097        objects = []
    8198        for model in sort_dependencies(app_list.items()):
     99            if model in excluded_objs:
     100                continue
    82101            if not model._meta.proxy and router.allow_syncdb(using, model):
    83102                objects.extend(model._default_manager.using(using).all())
    84103
  • docs/ref/django-admin.txt

     
    227227The :djadminopt:`--exclude` option may be provided to prevent specific
    228228applications from being dumped.
    229229
     230.. versionadded:: 1.3
     231
     232The :djadminopt:`--exclude` option may be provided to prevent specific
     233individual models, in the form of ``appname.ModelName``, from being dumped.
     234
    230235.. versionadded:: 1.1
    231236
    232237In addition to specifying application names, you can provide a list of
  • tests/modeltests/fixtures/tests.py

     
    2323
    2424class FixtureLoadingTests(TestCase):
    2525
    26     def _dumpdata_assert(self, args, output, format='json', natural_keys=False):
     26    def _dumpdata_assert(self, args, output, format='json', natural_keys=False,
     27                         exclude_list=[]):
    2728        new_io = StringIO.StringIO()
    28         management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io, 'use_natural_keys':natural_keys})
     29        management.call_command('dumpdata', *args, **{'format':format,
     30                                                      'stdout':new_io,
     31                                                      'use_natural_keys':natural_keys,
     32                                                      'exclude': exclude_list})
    2933        command_output = new_io.getvalue().strip()
    3034        self.assertEqual(command_output, output)
    3135
     
    150154        self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
    151155<django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16 16:00:00</field></object><object pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!</field><field type="DateTimeField" name="pub_date">2006-06-16 15:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it is</field><field type="DateTimeField" name="pub_date">2006-06-16 14:00:00</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag"><field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="1" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="1" model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as "Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object></django-objects>""", format='xml', natural_keys=True)
    152156
     157    def test_dumpdata_with_excludes(self):
     158        # Load fixture1 which has a site, two articles, and a category
     159        management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
     160       
     161        # Excluding fixtures app should only leave sites
     162        self._dumpdata_assert(
     163            ['sites', 'fixtures'],
     164            '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
     165            exclude_list=['fixtures'])
     166       
     167        # Excluding fixtures.Article should leave fixtures.category
     168        self._dumpdata_assert(
     169            ['sites', 'fixtures'],
     170            '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]',
     171            exclude_list=['fixtures.Article'])
     172
     173        # Excluding a bogus app should throw an error
     174        self.assertRaises(SystemExit,
     175                          self._dumpdata_assert,
     176                          ['fixtures', 'sites'],
     177                          '',
     178                          exclude_list=['foo_app'])
     179       
     180        # Excluding a bogus model should throw an error
     181        self.assertRaises(SystemExit,
     182                          self._dumpdata_assert,
     183                          ['fixtures', 'sites'],
     184                          '',
     185                          exclude_list=['fixtures.FooModel'])
     186
    153187    def test_compress_format_loading(self):
    154188        # Load fixture 4 (compressed), using format specification
    155189        management.call_command('loaddata', 'fixture4.json', verbosity=0, commit=False)
Back to Top