/polymorphic/polymorphic_model.py

https://bitbucket.org/bconstantin/django_polymorphic/ · Python · 190 lines · 158 code · 6 blank · 26 comment · 2 complexity · e41042214f2f45e995109bf221347617 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """
  3. Seamless Polymorphic Inheritance for Django Models
  4. ==================================================
  5. Please see README.rst and DOCS.rst for further information.
  6. Or on the Web:
  7. http://bserve.webhop.org/wiki/django_polymorphic
  8. http://github.com/bconstantin/django_polymorphic
  9. http://bitbucket.org/bconstantin/django_polymorphic
  10. Copyright:
  11. This code and affiliated files are (C) by Bert Constantin and individual contributors.
  12. Please see LICENSE and AUTHORS for more information.
  13. """
  14. from pprint import pprint
  15. import sys
  16. from compatibility_tools import defaultdict
  17. from django.db import models
  18. from django.contrib.contenttypes.models import ContentType
  19. from django import VERSION as django_VERSION
  20. from base import PolymorphicModelBase
  21. from manager import PolymorphicManager
  22. from query import PolymorphicQuerySet
  23. from showfields import ShowFieldType
  24. from query_translate import translate_polymorphic_Q_object
  25. ###################################################################################
  26. ### PolymorphicModel
  27. class PolymorphicModel(models.Model):
  28. """
  29. Abstract base class that provides polymorphic behaviour
  30. for any model directly or indirectly derived from it.
  31. For usage instructions & examples please see documentation.
  32. PolymorphicModel declares one field for internal use (polymorphic_ctype)
  33. and provides a polymorphic manager as the default manager
  34. (and as 'objects').
  35. PolymorphicModel overrides the save() and __init__ methods.
  36. If your derived class overrides any of these methods as well, then you need
  37. to take care that you correctly call the method of the superclass, like:
  38. super(YourClass,self).save(*args,**kwargs)
  39. """
  40. __metaclass__ = PolymorphicModelBase
  41. # for PolymorphicModelBase, so it can tell which models are polymorphic and which are not (duck typing)
  42. polymorphic_model_marker = True
  43. # for PolymorphicQuery, True => an overloaded __repr__ with nicer multi-line output is used by PolymorphicQuery
  44. polymorphic_query_multiline_output = False
  45. class Meta:
  46. abstract = True
  47. # avoid ContentType related field accessor clash (an error emitted by model validation)
  48. # we really should use both app_label and model name, but this is only possible since Django 1.2
  49. if django_VERSION[0] <= 1 and django_VERSION[1] <= 1:
  50. p_related_name_template = 'polymorphic_%(class)s_set'
  51. else:
  52. p_related_name_template = 'polymorphic_%(app_label)s.%(class)s_set'
  53. polymorphic_ctype = models.ForeignKey(ContentType, null=True, editable=False,
  54. related_name=p_related_name_template)
  55. # some applications want to know the name of the fields that are added to its models
  56. polymorphic_internal_model_fields = [ 'polymorphic_ctype' ]
  57. objects = PolymorphicManager()
  58. base_objects = models.Manager()
  59. @classmethod
  60. def translate_polymorphic_Q_object(self_class,q):
  61. return translate_polymorphic_Q_object(self_class,q)
  62. def pre_save_polymorphic(self):
  63. """Normally not needed.
  64. This function may be called manually in special use-cases. When the object
  65. is saved for the first time, we store its real class in polymorphic_ctype.
  66. When the object later is retrieved by PolymorphicQuerySet, it uses this
  67. field to figure out the real class of this object
  68. (used by PolymorphicQuerySet._get_real_instances)
  69. """
  70. if not self.polymorphic_ctype:
  71. self.polymorphic_ctype = ContentType.objects.get_for_model(self)
  72. def save(self, *args, **kwargs):
  73. """Overridden model save function which supports the polymorphism
  74. functionality (through pre_save_polymorphic)."""
  75. self.pre_save_polymorphic()
  76. return super(PolymorphicModel, self).save(*args, **kwargs)
  77. def get_real_instance_class(self):
  78. """Normally not needed.
  79. If a non-polymorphic manager (like base_objects) has been used to
  80. retrieve objects, then the real class/type of these objects may be
  81. determined using this method."""
  82. # the following line would be the easiest way to do this, but it produces sql queries
  83. #return self.polymorphic_ctype.model_class()
  84. # so we use the following version, which uses the CopntentType manager cache
  85. return ContentType.objects.get_for_id(self.polymorphic_ctype_id).model_class()
  86. def get_real_instance(self):
  87. """Normally not needed.
  88. If a non-polymorphic manager (like base_objects) has been used to
  89. retrieve objects, then the complete object with it's real class/type
  90. and all fields may be retrieved with this method.
  91. Each method call executes one db query (if necessary)."""
  92. real_model = self.get_real_instance_class()
  93. if real_model == self.__class__: return self
  94. return real_model.objects.get(pk=self.pk)
  95. def __init__(self, * args, ** kwargs):
  96. """Replace Django's inheritance accessor member functions for our model
  97. (self.__class__) with our own versions.
  98. We monkey patch them until a patch can be added to Django
  99. (which would probably be very small and make all of this obsolete).
  100. If we have inheritance of the form ModelA -> ModelB ->ModelC then
  101. Django creates accessors like this:
  102. - ModelA: modelb
  103. - ModelB: modela_ptr, modelb, modelc
  104. - ModelC: modela_ptr, modelb, modelb_ptr, modelc
  105. These accessors allow Django (and everyone else) to travel up and down
  106. the inheritance tree for the db object at hand.
  107. The original Django accessors use our polymorphic manager.
  108. But they should not. So we replace them with our own accessors that use
  109. our appropriate base_objects manager.
  110. """
  111. super(PolymorphicModel, self).__init__(*args, ** kwargs)
  112. if self.__class__.polymorphic_super_sub_accessors_replaced: return
  113. self.__class__.polymorphic_super_sub_accessors_replaced = True
  114. def create_accessor_function_for_model(model, accessor_name):
  115. def accessor_function(self):
  116. attr = model.base_objects.get(pk=self.pk)
  117. return attr
  118. return accessor_function
  119. subclasses_and_superclasses_accessors = self._get_inheritance_relation_fields_and_models()
  120. from django.db.models.fields.related import SingleRelatedObjectDescriptor, ReverseSingleRelatedObjectDescriptor
  121. for name,model in subclasses_and_superclasses_accessors.iteritems():
  122. orig_accessor = getattr(self.__class__, name, None)
  123. if type(orig_accessor) in [SingleRelatedObjectDescriptor,ReverseSingleRelatedObjectDescriptor]:
  124. #print >>sys.stderr, '---------- replacing',name, orig_accessor
  125. setattr(self.__class__, name, property(create_accessor_function_for_model(model, name)) )
  126. def _get_inheritance_relation_fields_and_models(self):
  127. """helper function for __init__:
  128. determine names of all Django inheritance accessor member functions for type(self)"""
  129. def add_model(model, as_ptr, result):
  130. name = model.__name__.lower()
  131. if as_ptr: name+='_ptr'
  132. result[name] = model
  133. def add_model_if_regular(model, as_ptr, result):
  134. if ( issubclass(model, models.Model) and model != models.Model
  135. and model != self.__class__
  136. and model != PolymorphicModel ):
  137. add_model(model,as_ptr,result)
  138. def add_all_super_models(model, result):
  139. add_model_if_regular(model, True, result)
  140. for b in model.__bases__:
  141. add_all_super_models(b, result)
  142. def add_all_sub_models(model, result):
  143. for b in model.__subclasses__():
  144. add_model_if_regular(b, False, result)
  145. result = {}
  146. add_all_super_models(self.__class__,result)
  147. add_all_sub_models(self.__class__,result)
  148. return result