Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 11KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. """
  2. Seamless Polymorphic Inheritance for Django Models
  3. """
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.db import models
  6. from django.db.models.fields.related import ForwardManyToOneDescriptor, ReverseOneToOneDescriptor
  7. from django.db.utils import DEFAULT_DB_ALIAS
  8. from polymorphic.compat import with_metaclass
  9. from .base import PolymorphicModelBase
  10. from .managers import PolymorphicManager
  11. from .query_translate import translate_polymorphic_Q_object
  12. ###################################################################################
  13. # PolymorphicModel
  14. class PolymorphicTypeUndefined(LookupError):
  15. pass
  16. class PolymorphicTypeInvalid(RuntimeError):
  17. pass
  18. class PolymorphicModel(with_metaclass(PolymorphicModelBase, models.Model)):
  19. """
  20. Abstract base class that provides polymorphic behaviour
  21. for any model directly or indirectly derived from it.
  22. PolymorphicModel declares one field for internal use (:attr:`polymorphic_ctype`)
  23. and provides a polymorphic manager as the default manager (and as 'objects').
  24. """
  25. # for PolymorphicModelBase, so it can tell which models are polymorphic and which are not (duck typing)
  26. polymorphic_model_marker = True
  27. # for PolymorphicQuery, True => an overloaded __repr__ with nicer multi-line output is used by PolymorphicQuery
  28. polymorphic_query_multiline_output = False
  29. # avoid ContentType related field accessor clash (an error emitted by model validation)
  30. #: The model field that stores the :class:`~django.contrib.contenttypes.models.ContentType` reference to the actual class.
  31. polymorphic_ctype = models.ForeignKey(
  32. ContentType,
  33. null=True,
  34. editable=False,
  35. on_delete=models.CASCADE,
  36. related_name="polymorphic_%(app_label)s.%(class)s_set+",
  37. )
  38. # some applications want to know the name of the fields that are added to its models
  39. polymorphic_internal_model_fields = ["polymorphic_ctype"]
  40. # Note that Django 1.5 removes these managers because the model is abstract.
  41. # They are pretended to be there by the metaclass in PolymorphicModelBase.get_inherited_managers()
  42. objects = PolymorphicManager()
  43. class Meta:
  44. abstract = True
  45. base_manager_name = "objects"
  46. @classmethod
  47. def translate_polymorphic_Q_object(cls, q):
  48. return translate_polymorphic_Q_object(cls, q)
  49. def pre_save_polymorphic(self, using=DEFAULT_DB_ALIAS):
  50. """
  51. Make sure the ``polymorphic_ctype`` value is correctly set on this model.
  52. """
  53. # This function may be called manually in special use-cases. When the object
  54. # is saved for the first time, we store its real class in polymorphic_ctype.
  55. # When the object later is retrieved by PolymorphicQuerySet, it uses this
  56. # field to figure out the real class of this object
  57. # (used by PolymorphicQuerySet._get_real_instances)
  58. if not self.polymorphic_ctype_id:
  59. self.polymorphic_ctype = ContentType.objects.db_manager(using).get_for_model(
  60. self, for_concrete_model=False
  61. )
  62. pre_save_polymorphic.alters_data = True
  63. def save(self, *args, **kwargs):
  64. """Calls :meth:`pre_save_polymorphic` and saves the model."""
  65. using = kwargs.get("using", self._state.db or DEFAULT_DB_ALIAS)
  66. self.pre_save_polymorphic(using=using)
  67. return super().save(*args, **kwargs)
  68. save.alters_data = True
  69. def get_real_instance_class(self):
  70. """
  71. Return the actual model type of the object.
  72. If a non-polymorphic manager (like base_objects) has been used to
  73. retrieve objects, then the real class/type of these objects may be
  74. determined using this method.
  75. """
  76. if self.polymorphic_ctype_id is None:
  77. raise PolymorphicTypeUndefined(
  78. (
  79. "The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
  80. "If you created models outside polymorphic, e.g. through an import or migration, "
  81. "make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
  82. ).format(self.__class__.__name__, self.pk)
  83. )
  84. # the following line would be the easiest way to do this, but it produces sql queries
  85. # return self.polymorphic_ctype.model_class()
  86. # so we use the following version, which uses the ContentType manager cache.
  87. # Note that model_class() can return None for stale content types;
  88. # when the content type record still exists but no longer refers to an existing model.
  89. model = (
  90. ContentType.objects.db_manager(self._state.db)
  91. .get_for_id(self.polymorphic_ctype_id)
  92. .model_class()
  93. )
  94. # Protect against bad imports (dumpdata without --natural) or other
  95. # issues missing with the ContentType models.
  96. if (
  97. model is not None
  98. and not issubclass(model, self.__class__)
  99. and (
  100. self.__class__._meta.proxy_for_model is None
  101. or not issubclass(model, self.__class__._meta.proxy_for_model)
  102. )
  103. ):
  104. raise PolymorphicTypeInvalid(
  105. "ContentType {} for {} #{} does not point to a subclass!".format(
  106. self.polymorphic_ctype_id, model, self.pk
  107. )
  108. )
  109. return model
  110. def get_real_concrete_instance_class_id(self):
  111. model_class = self.get_real_instance_class()
  112. if model_class is None:
  113. return None
  114. return (
  115. ContentType.objects.db_manager(self._state.db)
  116. .get_for_model(model_class, for_concrete_model=True)
  117. .pk
  118. )
  119. def get_real_concrete_instance_class(self):
  120. model_class = self.get_real_instance_class()
  121. if model_class is None:
  122. return None
  123. return (
  124. ContentType.objects.db_manager(self._state.db)
  125. .get_for_model(model_class, for_concrete_model=True)
  126. .model_class()
  127. )
  128. def get_real_instance(self):
  129. """
  130. Upcast an object to it's actual type.
  131. If a non-polymorphic manager (like base_objects) has been used to
  132. retrieve objects, then the complete object with it's real class/type
  133. and all fields may be retrieved with this method.
  134. .. note::
  135. Each method call executes one db query (if necessary).
  136. Use the :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances`
  137. to upcast a complete list in a single efficient query.
  138. """
  139. real_model = self.get_real_instance_class()
  140. if real_model == self.__class__:
  141. return self
  142. return real_model.objects.db_manager(self._state.db).get(pk=self.pk)
  143. def __init__(self, *args, **kwargs):
  144. """Replace Django's inheritance accessor member functions for our model
  145. (self.__class__) with our own versions.
  146. We monkey patch them until a patch can be added to Django
  147. (which would probably be very small and make all of this obsolete).
  148. If we have inheritance of the form ModelA -> ModelB ->ModelC then
  149. Django creates accessors like this:
  150. - ModelA: modelb
  151. - ModelB: modela_ptr, modelb, modelc
  152. - ModelC: modela_ptr, modelb, modelb_ptr, modelc
  153. These accessors allow Django (and everyone else) to travel up and down
  154. the inheritance tree for the db object at hand.
  155. The original Django accessors use our polymorphic manager.
  156. But they should not. So we replace them with our own accessors that use
  157. our appropriate base_objects manager.
  158. """
  159. super().__init__(*args, **kwargs)
  160. if self.__class__.polymorphic_super_sub_accessors_replaced:
  161. return
  162. self.__class__.polymorphic_super_sub_accessors_replaced = True
  163. def create_accessor_function_for_model(model, accessor_name):
  164. def accessor_function(self):
  165. objects = getattr(model, "_base_objects", model.objects)
  166. attr = objects.get(pk=self.pk)
  167. return attr
  168. return accessor_function
  169. subclasses_and_superclasses_accessors = self._get_inheritance_relation_fields_and_models()
  170. for name, model in subclasses_and_superclasses_accessors.items():
  171. # Here be dragons.
  172. orig_accessor = getattr(self.__class__, name, None)
  173. if issubclass(
  174. type(orig_accessor),
  175. (ReverseOneToOneDescriptor, ForwardManyToOneDescriptor),
  176. ):
  177. setattr(
  178. self.__class__,
  179. name,
  180. property(create_accessor_function_for_model(model, name)),
  181. )
  182. def _get_inheritance_relation_fields_and_models(self):
  183. """helper function for __init__:
  184. determine names of all Django inheritance accessor member functions for type(self)"""
  185. def add_model(model, field_name, result):
  186. result[field_name] = model
  187. def add_model_if_regular(model, field_name, result):
  188. if (
  189. issubclass(model, models.Model)
  190. and model != models.Model
  191. and model != self.__class__
  192. and model != PolymorphicModel
  193. ):
  194. add_model(model, field_name, result)
  195. def add_all_super_models(model, result):
  196. for super_cls, field_to_super in model._meta.parents.items():
  197. if field_to_super is not None:
  198. # if not a link to a proxy model, the field on model can have
  199. # a different name to super_cls._meta.module_name, when the field
  200. # is created manually using 'parent_link'
  201. field_name = field_to_super.name
  202. add_model_if_regular(super_cls, field_name, result)
  203. add_all_super_models(super_cls, result)
  204. def add_all_sub_models(super_cls, result):
  205. # go through all subclasses of model
  206. for sub_cls in super_cls.__subclasses__():
  207. # super_cls may not be in sub_cls._meta.parents if super_cls is a proxy model
  208. if super_cls in sub_cls._meta.parents:
  209. # get the field that links sub_cls to super_cls
  210. field_to_super = sub_cls._meta.parents[super_cls]
  211. # if filed_to_super is not a link to a proxy model
  212. if field_to_super is not None:
  213. super_to_sub_related_field = field_to_super.remote_field
  214. if super_to_sub_related_field.related_name is None:
  215. # if related name is None the related field is the name of the subclass
  216. to_subclass_fieldname = sub_cls.__name__.lower()
  217. else:
  218. # otherwise use the given related name
  219. to_subclass_fieldname = super_to_sub_related_field.related_name
  220. add_model_if_regular(sub_cls, to_subclass_fieldname, result)
  221. result = {}
  222. add_all_super_models(self.__class__, result)
  223. add_all_sub_models(self.__class__, result)
  224. return result