File: polymorphic_model.py

package info (click to toggle)
django-polymorphic 0.6-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 436 kB
  • ctags: 586
  • sloc: python: 2,208; makefile: 142
file content (213 lines) | stat: -rw-r--r-- 9,223 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
==================================================

Please see README.rst and DOCS.rst for further information.

Or on the Web:
http://chrisglass.github.com/django_polymorphic/
http://github.com/chrisglass/django_polymorphic

Copyright:
This code and affiliated files are (C) by Bert Constantin and individual contributors.
Please see LICENSE and AUTHORS for more information.
"""
from __future__ import absolute_import

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils import six

from .base import PolymorphicModelBase
from .manager import PolymorphicManager
from .query_translate import translate_polymorphic_Q_object


###################################################################################
### PolymorphicModel

class PolymorphicModel(six.with_metaclass(PolymorphicModelBase, models.Model)):
    """
    Abstract base class that provides polymorphic behaviour
    for any model directly or indirectly derived from it.

    For usage instructions & examples please see documentation.

    PolymorphicModel declares one field for internal use (polymorphic_ctype)
    and provides a polymorphic manager as the default manager
    (and as 'objects').

    PolymorphicModel overrides the save() and __init__ methods.

    If your derived class overrides any of these methods as well, then you need
    to take care that you correctly call the method of the superclass, like:

        super(YourClass,self).save(*args,**kwargs)
    """

    # for PolymorphicModelBase, so it can tell which models are polymorphic and which are not (duck typing)
    polymorphic_model_marker = True

    # for PolymorphicQuery, True => an overloaded __repr__ with nicer multi-line output is used by PolymorphicQuery
    polymorphic_query_multiline_output = False

    class Meta:
        abstract = True

    # avoid ContentType related field accessor clash (an error emitted by model validation)
    polymorphic_ctype = models.ForeignKey(ContentType, null=True, editable=False,
                                related_name='polymorphic_%(app_label)s.%(class)s_set')

    # some applications want to know the name of the fields that are added to its models
    polymorphic_internal_model_fields = ['polymorphic_ctype']

    # Note that Django 1.5 removes these managers because the model is abstract.
    # They are pretended to be there by the metaclass in PolymorphicModelBase.get_inherited_managers()
    objects = PolymorphicManager()
    base_objects = models.Manager()

    @classmethod
    def translate_polymorphic_Q_object(self_class, q):
        return translate_polymorphic_Q_object(self_class, q)

    def pre_save_polymorphic(self):
        """Normally not needed.
        This function may be called manually in special use-cases. When the object
        is saved for the first time, we store its real class in polymorphic_ctype.
        When the object later is retrieved by PolymorphicQuerySet, it uses this
        field to figure out the real class of this object
        (used by PolymorphicQuerySet._get_real_instances)
        """
        if not self.polymorphic_ctype_id:
            self.polymorphic_ctype = ContentType.objects.get_for_model(self, for_concrete_model=False)
    pre_save_polymorphic.alters_data = True

    def save(self, *args, **kwargs):
        """Overridden model save function which supports the polymorphism
        functionality (through pre_save_polymorphic)."""
        self.pre_save_polymorphic()
        return super(PolymorphicModel, self).save(*args, **kwargs)
    save.alters_data = True

    def get_real_instance_class(self):
        """
        Normally not needed.
        If a non-polymorphic manager (like base_objects) has been used to
        retrieve objects, then the real class/type of these objects may be
        determined using this method.
        """
        # the following line would be the easiest way to do this, but it produces sql queries
        # return self.polymorphic_ctype.model_class()
        # so we use the following version, which uses the ContentType manager cache.
        # Note that model_class() can return None for stale content types;
        # when the content type record still exists but no longer refers to an existing model.
        try:
            model = ContentType.objects.get_for_id(self.polymorphic_ctype_id).model_class()
        except AttributeError:
            # Django <1.6 workaround
            return None

        # Protect against bad imports (dumpdata without --natural) or other
        # issues missing with the ContentType models.
        if model is not None \
        and not issubclass(model, self.__class__) \
        and not issubclass(model, self.__class__._meta.proxy_for_model):
            raise RuntimeError("ContentType {0} for {1} #{2} does not point to a subclass!".format(
                self.polymorphic_ctype_id, model, self.pk,
            ))
        return model

    def get_real_concrete_instance_class_id(self):
        model_class = self.get_real_instance_class()
        if model_class is None:
            return None
        return ContentType.objects.get_for_model(model_class, for_concrete_model=True).pk

    def get_real_concrete_instance_class(self):
        model_class = self.get_real_instance_class()
        if model_class is None:
            return None
        return ContentType.objects.get_for_model(model_class, for_concrete_model=True).model_class()

    def get_real_instance(self):
        """Normally not needed.
        If a non-polymorphic manager (like base_objects) has been used to
        retrieve objects, then the complete object with it's real class/type
        and all fields may be retrieved with this method.
        Each method call executes one db query (if necessary)."""
        real_model = self.get_real_instance_class()
        if real_model == self.__class__:
            return self
        return real_model.objects.get(pk=self.pk)

    def __init__(self, * args, ** kwargs):
        """Replace Django's inheritance accessor member functions for our model
        (self.__class__) with our own versions.
        We monkey patch them until a patch can be added to Django
        (which would probably be very small and make all of this obsolete).

        If we have inheritance of the form ModelA -> ModelB ->ModelC then
        Django creates accessors like this:
        - ModelA: modelb
        - ModelB: modela_ptr, modelb, modelc
        - ModelC: modela_ptr, modelb, modelb_ptr, modelc

        These accessors allow Django (and everyone else) to travel up and down
        the inheritance tree for the db object at hand.

        The original Django accessors use our polymorphic manager.
        But they should not. So we replace them with our own accessors that use
        our appropriate base_objects manager.
        """
        super(PolymorphicModel, self).__init__(*args, ** kwargs)

        if self.__class__.polymorphic_super_sub_accessors_replaced:
            return
        self.__class__.polymorphic_super_sub_accessors_replaced = True

        def create_accessor_function_for_model(model, accessor_name):
            def accessor_function(self):
                attr = model.base_objects.get(pk=self.pk)
                return attr
            return accessor_function

        subclasses_and_superclasses_accessors = self._get_inheritance_relation_fields_and_models()

        from django.db.models.fields.related import SingleRelatedObjectDescriptor, ReverseSingleRelatedObjectDescriptor
        for name, model in subclasses_and_superclasses_accessors.items():
            orig_accessor = getattr(self.__class__, name, None)
            if type(orig_accessor) in [SingleRelatedObjectDescriptor, ReverseSingleRelatedObjectDescriptor]:
                #print >>sys.stderr, '---------- replacing', name, orig_accessor, '->', model
                setattr(self.__class__, name, property(create_accessor_function_for_model(model, name)))

    def _get_inheritance_relation_fields_and_models(self):
        """helper function for __init__:
        determine names of all Django inheritance accessor member functions for type(self)"""

        def add_model(model, as_ptr, result):
            name = model.__name__.lower()
            if as_ptr:
                name += '_ptr'
            result[name] = model

        def add_model_if_regular(model, as_ptr, result):
            if (issubclass(model, models.Model)
                and model != models.Model
                and model != self.__class__
                and model != PolymorphicModel):
                add_model(model, as_ptr, result)

        def add_all_super_models(model, result):
            add_model_if_regular(model, True, result)
            for b in model.__bases__:
                add_all_super_models(b, result)

        def add_all_sub_models(model, result):
            for b in model.__subclasses__():
                add_model_if_regular(b, False, result)

        result = {}
        add_all_super_models(self.__class__, result)
        add_all_sub_models(self.__class__, result)
        return result