Django

Code

root/django/trunk/django/contrib/contenttypes/management.py

Revision 8223, 1.7 kB (checked in by jacob, 4 months ago)

Major refactoring of django.dispatch with an eye towards speed. The net result is that signals are up to 90% faster.

Though some attempts and backwards-compatibility were made, speed trumped compatibility. Thus, as usual, check BackwardsIncompatibleChanges for the complete list of backwards-incompatible changes.

Thanks to Jeremy Dunck and Keith Busell for the bulk of the work; some ideas from Brian Herring's previous work (refs #4561) were incorporated.

Documentation is, sigh, still forthcoming.

Fixes #6814 and #3951 (with the new dispatch_uid argument to connect).

  • Property svn:eol-style set to native
Line 
1 from django.contrib.contenttypes.models import ContentType
2 from django.db.models import get_apps, get_models, signals
3 from django.utils.encoding import smart_unicode
4
5 def update_contenttypes(app, created_models, verbosity=2, **kwargs):
6     """
7     Creates content types for models in the given app, removing any model
8     entries that no longer have a matching model class.
9     """
10     ContentType.objects.clear_cache()
11     content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2]))
12     app_models = get_models(app)
13     if not app_models:
14         return
15     for klass in app_models:
16         opts = klass._meta
17         try:
18             ct = ContentType.objects.get(app_label=opts.app_label,
19                                          model=opts.object_name.lower())
20             content_types.remove(ct)
21         except ContentType.DoesNotExist:
22             ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
23                 app_label=opts.app_label, model=opts.object_name.lower())
24             ct.save()
25             if verbosity >= 2:
26                 print "Adding content type '%s | %s'" % (ct.app_label, ct.model)
27     # The presence of any remaining content types means the supplied app has an
28     # undefined model and can safely be removed, which cascades to also remove
29     # related permissions.
30     for ct in content_types:
31         if verbosity >= 2:
32             print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model)
33         ct.delete()
34
35 def update_all_contenttypes(verbosity=2):
36     for app in get_apps():
37         update_contenttypes(app, None, verbosity)
38
39 signals.post_syncdb.connect(update_contenttypes)
40
41 if __name__ == "__main__":
42     update_all_contenttypes()
Note: See TracBrowser for help on using the browser.