Advertisement
Guest User

freinhard

a guest
Aug 13th, 2010
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Diff 5.37 KB | None | 0 0
  1. diff --git a/src/reversion/management/commands/__init__.py b/src/reversion/management/commands/__init__.py
  2. new file mode 100644
  3. index 0000000..e69de29
  4. diff --git a/src/reversion/management/commands/reversion_createinitial.py b/src/reversion/management/commands/reversion_createinitial.py
  5. new file mode 100644
  6. index 0000000..297a1e3
  7. --- /dev/null
  8. +++ b/src/reversion/management/commands/reversion_createinitial.py
  9. @@ -0,0 +1,97 @@
  10. +# -*- coding: utf-8 -*-
  11. +import sys
  12. +
  13. +from django import VERSION
  14. +from django.contrib import admin
  15. +from django.contrib.contenttypes.models import ContentType
  16. +from django.core.exceptions import ImproperlyConfigured
  17. +from django.core.management.base import BaseCommand
  18. +from django.core.management.base import CommandError
  19. +from django.db import models
  20. +from django.utils.importlib import import_module
  21. +from django.utils.datastructures import SortedDict
  22. +
  23. +from reversion import models as reversion_app, revision
  24. +from reversion.models import Version
  25. +from reversion.management import version_save
  26. +
  27. +class Command(BaseCommand):
  28. +    args = '[appname, appname.ModelName, ...]'
  29. +    help = 'Creates initial revisions for a given app [and model].'
  30. +
  31. +    def __init__(self, *args, **kwargs):
  32. +        super(Command, self).__init__(*args, **kwargs)
  33. +        # be safe for future django versions
  34. +        if VERSION[0] == 1 and VERSION[1] <= 2:
  35. +            self.stdout = sys.stdout
  36. +
  37. +    def handle(self, *app_labels, **options):
  38. +        if len(app_labels) == 0:
  39. +            raise CommandError ('No applications or models given.')
  40. +        else:
  41. +            # parse command line options
  42. +            app_list = SortedDict()
  43. +            for label in app_labels:
  44. +                try:
  45. +                    app_label, model_label = label.split('.')
  46. +                    try:
  47. +                        app = models.get_app(app_label)
  48. +                    except ImproperlyConfigured:
  49. +                        raise CommandError("Unknown application: %s" % app_label)
  50. +
  51. +                    model_class = models.get_model(app_label, model_label)
  52. +                    if model_class is None:
  53. +                        raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
  54. +                    if app in app_list.keys():
  55. +                        if app_list[app] and model_class not in app_list[app]:
  56. +                            app_list[app].append(model_class)
  57. +                    else:
  58. +                        app_list[app] = [model_class]
  59. +                except ValueError:
  60. +                    # This is just an app - no model qualifier
  61. +                    app_label = label
  62. +                    try:
  63. +                        app = models.get_app(app_label)
  64. +                        if not app in app_list.keys():
  65. +                            app_list[app] = []
  66. +                        for model_class in models.get_models(app):
  67. +                            if not model_class in app_list[app]:
  68. +                                app_list[app].append(model_class)
  69. +                    except ImproperlyConfigured:
  70. +                        raise CommandError("Unknown application: %s" % app_label)
  71. +            # create revisions      
  72. +            for app,model_classes in app_list.items ():
  73. +                for model_class in model_classes:
  74. +                    self.create_initial_revisions (app, model_class)
  75. +
  76. +    def create_initial_revisions(self, app, model_class, verbosity=2, **kwargs):
  77. +        """
  78. +        all stolen :)
  79. +        """
  80. +        # Import the relevant admin module.
  81. +        try:
  82. +            import_module("%s.admin" % app.__name__.rsplit(".", 1)[0])
  83. +        except ImportError:
  84. +            pass
  85. +        # Check all models for empty revisions.
  86. +        if revision.is_registered(model_class):
  87. +            content_type = ContentType.objects.get_for_model(model_class)
  88. +            # Get the id for all models that have not got at least one revision.
  89. +            # HACK: This join can't be done in the database, for potential incompatibilities
  90. +            # between unicode object_ids and integer pks on strict backends like postgres.
  91. +            versioned_ids = frozenset(Version.objects.filter(content_type=content_type).values_list("object_id", flat=True).distinct().iterator())
  92. +            all_ids = frozenset(unicode(id) for id in model_class._default_manager.values_list("pk", flat=True).iterator())
  93. +            unversioned_ids = all_ids - versioned_ids
  94. +            # Create the initial revision for all unversioned models.
  95. +            created_count = 0
  96. +            for unversioned_obj in model_class._default_manager.filter(pk__in=unversioned_ids).iterator():
  97. +                version_save(unversioned_obj)
  98. +                created_count += 1
  99. +            # Print out a message, if feeling verbose.
  100. +            if created_count > 0 and verbosity >= 2:
  101. +                self.stdout.write (u"Created %s initial revisions for model %s.\n" % (created_count, model_class._meta.verbose_name))
  102. +        else:
  103. +            if verbosity >= 2:
  104. +                self.stdout.write (u"Model %s is not registered.\n"  % (model_class._meta.verbose_name))
  105. +
  106. +#kate: indent-mode python; indent-width 4; indent-spaces on; replace-tabs on; line-numbers on; folding-markers on;#kate: indent-mode python; indent-width 4; indent-spaces on; replace-tabs on; line-numbers on; folding-markers on;
  107. \ No newline at end of file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement