/polymorphic/manager.py

https://bitbucket.org/bconstantin/django_polymorphic/ · Python · 36 lines · 15 code · 7 blank · 14 comment · 3 complexity · 0b8b55b7e230b9683f3567eb8dce2f39 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """ PolymorphicManager
  3. Please see README.rst or DOCS.rst or http://bserve.webhop.org/wiki/django_polymorphic
  4. """
  5. from django.db import models
  6. from query import PolymorphicQuerySet
  7. class PolymorphicManager(models.Manager):
  8. """
  9. Manager for PolymorphicModel
  10. Usually not explicitly needed, except if a custom manager or
  11. a custom queryset class is to be used.
  12. """
  13. use_for_related_fields = True
  14. def __init__(self, queryset_class=None, *args, **kwrags):
  15. if not queryset_class: self.queryset_class = PolymorphicQuerySet
  16. else: self.queryset_class = queryset_class
  17. super(PolymorphicManager, self).__init__(*args, **kwrags)
  18. def get_query_set(self):
  19. return self.queryset_class(self.model)
  20. # Proxy all unknown method calls to the queryset, so that its members are
  21. # directly accessible as PolymorphicModel.objects.*
  22. # The advantage of this method is that not yet known member functions of derived querysets will be proxied as well.
  23. # We exclude any special functions (__) from this automatic proxying.
  24. def __getattr__(self, name):
  25. if name.startswith('__'): return super(PolymorphicManager, self).__getattr__(self, name)
  26. return getattr(self.get_query_set(), name)
  27. def __unicode__(self):
  28. return self.__class__.__name__ + ' (PolymorphicManager) using ' + self.queryset_class.__name__