Code

Ticket #16330: dumpdata-primary-keys2.diff

File dumpdata-primary-keys2.diff, 4.0 KB (added by rm_, 2 years ago)

Diffed against latest trunk, coding style cleanup, some code motion in dumpdata to follow how the other options are checked, some rewording of the help text

Line 
1Index: django/core/management/commands/dumpdata.py
2===================================================================
3--- django/core/management/commands/dumpdata.py (revisione 17334)
4+++ django/core/management/commands/dumpdata.py (copia locale)
5@@ -5,6 +5,8 @@
6 from django.utils.datastructures import SortedDict
7 
8 from optparse import make_option
9+import itertools
10+import sys
11 
12 class Command(BaseCommand):
13     option_list = BaseCommand.option_list + (
14@@ -21,6 +23,8 @@
15             help='Use natural keys if they are available.'),
16         make_option('-a', '--all', action='store_true', dest='use_base_manager', default=False,
17             help="Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager."),
18+        make_option('--pks', dest='primary_keys', action='append', default=[],
19+            help="Only dump objects with given primary keys. Accepts a space seperated list of keys or '-' to read from stdin. This is mostly useful when dumping only a single model."),
20     )
21     help = ("Output the contents of the database as a fixture of the given "
22             "format (using each model's default manager unless --all is "
23@@ -34,6 +38,7 @@
24         indent = options.get('indent')
25         using = options.get('database')
26         excludes = options.get('exclude')
27+        pks = options.get('primary_keys')
28         show_traceback = options.get('traceback')
29         use_natural_keys = options.get('use_natural_keys')
30         use_base_manager = options.get('use_base_manager')
31@@ -54,6 +59,12 @@
32                 except ImproperlyConfigured:
33                     raise CommandError('Unknown app in excludes: %s' % exclude)
34 
35+        if pks == ['-']:
36+            # Read from Stdin
37+            primary_keys = sys.stdin.read().split()
38+        else:
39+            primary_keys = list(itertools.chain(*[pk.split() for pk in pks]))
40+
41         if len(app_labels) == 0:
42             app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_apps)
43         else:
44@@ -104,9 +115,12 @@
45                 continue
46             if not model._meta.proxy and router.allow_syncdb(using, model):
47                 if use_base_manager:
48-                    objects.extend(model._base_manager.using(using).all())
49+                    queryset = model._base_manager.using(using).all()
50                 else:
51-                    objects.extend(model._default_manager.using(using).all())
52+                    queryset = model._default_manager.using(using).all()
53+                if primary_keys:
54+                    queryset = queryset.filter(pk__in=primary_keys)
55+                objects.extend(queryset)
56 
57         try:
58             return serializers.serialize(format, objects, indent=indent,
59Index: tests/regressiontests/fixtures_regress/tests.py
60===================================================================
61--- tests/regressiontests/fixtures_regress/tests.py     (revisione 17334)
62+++ tests/regressiontests/fixtures_regress/tests.py     (copia locale)
63@@ -16,6 +16,7 @@
64 from django.db.models import signals
65 from django.test import (TestCase, TransactionTestCase, skipIfDBFeature,
66     skipUnlessDBFeature)
67+from django.utils import simplejson
68 
69 from .models import (Animal, Stuff, Absolute, Parent, Child, Article, Widget,
70     Store, Person, Book, NKChild, RefToNKChild, Circle1, Circle2, Circle3,
71@@ -341,6 +342,20 @@
72         self.assertTrue(emu_json in data)
73         self.assertTrue(platypus_json in data)
74 
75+        stdout = StringIO()
76+        management.call_command(
77+            'dumpdata',
78+            'fixtures_regress.animal',
79+            format='json',
80+            stdout=stdout,
81+            primary_keys=['1 10']
82+        )
83+        data = stdout.getvalue()
84+        json = simplejson.loads(data)
85+        self.assertEqual(len(json), 2)
86+        keys = sorted([item['pk'] for item in json])
87+        self.assertEqual(keys, [1, 10])
88+
89     def test_proxy_model_included(self):
90         """
91         Regression for #11428 - Proxy models aren't included when you dumpdata