Debian Codegraph @

docs/advanced.rst

raw
1 .. _advanced-features:
2
3 Advanced Features
4 =================
5
6 In the examples below, these models are being used:
7
8 .. code-block:: python
9
10 from django.db import models
11 from polymorphic.models import PolymorphicModel
12
13 class ModelA(PolymorphicModel):
14 field1 = models.CharField(max_length=10)
15
16 class ModelB(ModelA):
17 field2 = models.CharField(max_length=10)
18
19 class ModelC(ModelB):
20 field3 = models.CharField(max_length=10)
21
22
23 Filtering for classes (equivalent to python's :func:`isinstance`):
24 ------------------------------------------------------------------
25
26 .. code-block:: python
27
28 >>> ModelA.objects.instance_of(ModelB)
29 [ <ModelB: id 2, field1 (CharField), field2 (CharField)>,
30 <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]
31
32 In general, including or excluding parts of the inheritance tree:
33
34 .. code-block:: python
35
36 ModelA.objects.instance_of(ModelB [, ModelC ...])
37 ModelA.objects.not_instance_of(ModelB [, ModelC ...])
38
39 You can also use this feature in Q-objects (with the same result as above):
40
41 .. code-block:: python
42
43 >>> ModelA.objects.filter( Q(instance_of=ModelB) )
44
45
46 Polymorphic filtering (for fields in inherited classes)
47 -------------------------------------------------------
48
49 For example, cherry-picking objects from multiple derived classes anywhere in the inheritance tree,
50 using Q objects (with the syntax: ``exact model name + three _ + field name``):
51
52 .. code-block:: python
53
54 >>> ModelA.objects.filter( Q(ModelB___field2 = 'B2') | Q(ModelC___field3 = 'C3') )
55 [ <ModelB: id 2, field1 (CharField), field2 (CharField)>,
56 <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]
57
58
59 Combining Querysets
60 -------------------
61
62 Querysets could now be regarded as object containers that allow the
63 aggregation of different object types, very similar to python
64 lists - as long as the objects are accessed through the manager of
65 a common base class:
66
67 .. code-block:: python
68
69 >>> Base.objects.instance_of(ModelX) | Base.objects.instance_of(ModelY)
70
71 [ <ModelX: id 1, field_x (CharField)>,
72 <ModelY: id 2, field_y (CharField)> ]
73
74
75 ManyToManyField, ForeignKey, OneToOneField
76 ------------------------------------------
77
78 Relationship fields referring to polymorphic models work as
79 expected: like polymorphic querysets they now always return the
80 referred objects with the same type/class these were created and
81 saved as.
82
83 E.g., if in your model you define:
84
85 .. code-block:: python
86
87 field1 = OneToOneField(ModelA)
88
89 then field1 may now also refer to objects of type ``ModelB`` or ``ModelC``.
90
91 A :class:`~django.db.models.ManyToManyField` example:
92
93 .. code-block:: python
94
95 # The model holding the relation may be any kind of model, polymorphic or not
96 class RelatingModel(models.Model):
97
98 # ManyToMany relation to a polymorphic model
99 many2many = models.ManyToManyField('ModelA')
100
101 >>> o=RelatingModel.objects.create()
102 >>> o.many2many.add(ModelA.objects.get(id=1))
103 >>> o.many2many.add(ModelB.objects.get(id=2))
104 >>> o.many2many.add(ModelC.objects.get(id=3))
105
106 >>> o.many2many.all()
107 [ <ModelA: id 1, field1 (CharField)>,
108 <ModelB: id 2, field1 (CharField), field2 (CharField)>,
109 <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]
110
111 Copying Polymorphic objects
112 ---------------------------
113
114 **Copying polymorphic models is no different than copying regular multi-table models.** You have
115 two options:
116
117 1. Use :meth:`~django.db.models.query.QuerySet.create` and provide all field values from the
118 original instance except the primary key(s).
119 2. Set the primary key attribute, and parent table pointers at all levels of inheritance to ``None``
120 and call :meth:`~django.db.models.Model.save`.
121
122 The Django documentation :ref:`offers some discussion on copying
123 <topics/db/queries:copying model instances>`, including the complexity around related fields and
124 multi-table inheritance. :pypi:`django-polymorphic` offers a utility function
125 :func:`~polymorphic.utils.prepare_for_copy` that resets all necessary fields on a model instance to
126 prepare it for copying:
127
128 .. code-block:: python
129
130 from polymorphic.utils import prepare_for_copy
131
132 obj = ModelB.objects.first()
133 prepare_for_copy(obj)
134 obj.save()
135 # obj is now a copy of the original ModelB instance
136
137
138 Working with Fixtures
139 ---------------------
140
141 Polymorphic models work with Django's :django-admin:`dumpdata` and :django-admin:`loaddata`
142 commands just as regular models do. There are two important considerations:
143
144 1. Polymorphic models are multi-table models and :django-admin:`dumpdata` serializes each table
145 separately. :pypi:`django-polymorphic` `does it's best
146 <https://github.com/django-commons/django-polymorphic/pull/814>`_ to ensure non-polymorphic managers
147 are used when creating fixtures but there may be edge cases where this fails. If you override
148 :django-admin:`dumpdata` you must make sure any polymorphic managers encountered
149 :meth:`toggle polymorphism off <polymorphic.managers.PolymorphicQuerySet.non_polymorphic>`. Other
150 usual multi-table model caveats apply. If you serialize a subset of tables in the model
151 inheritance you may generate corrupt data or "upcast" your models if child tables were omitted.
152 2. Polymorphic models rely on the :class:`~django.contrib.contenttypes.models.ContentType`
153 framework. When serializing and deserializing polymorphic models, the
154 ``polymorphic_ctype`` field must be handled correctly. If there is any question about if the
155 content type primary keys are or will be different between the source and target database you
156 should use the :option:`--natural-foreign <dumpdata.--natural-foreign>` flag to serialize those
157 relations by-value. Polymorphism introduces no special consideration here - any model using
158 contenttypes, polymorphic or not, must handle this correctly.
159
160 .. note::
161
162 Prior documentation urged users to use both :option:`--natural-primary <dumpdata.--natural-primary>`
163 and :option:`--natural-foreign <dumpdata.--natural-foreign>` flags when dumping polymorphic
164 models. This is not necessary and only needs to be done when the primary keys are not guaranteed
165 to match or be available at the target database.
166
167 Loading Fixtures (loaddata)
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
170 Fixtures should be loadable as normal with :django-admin:`loaddata`. However, if there are problems
171 with the ``polymorphic_ctype`` references, you may fix them using
172 :func:`~polymorphic.utils.reset_polymorphic_ctype`:
173
174 .. code-block:: python
175
176 from polymorphic.utils import reset_polymorphic_ctype
177 from myapp.models import Animal, Dog, Cat
178
179 # Reset polymorphic_ctype for all models in the inheritance tree
180 reset_polymorphic_ctype(Animal, Dog, Cat)
181
182 Using Third Party Models (without modifying them)
183 -------------------------------------------------
184
185 Third party models can be used as polymorphic models without
186 restrictions by subclassing them. E.g. using a third party
187 model as the root of a polymorphic inheritance tree:
188
189 .. code-block:: python
190
191 from thirdparty import ThirdPartyModel
192
193 class MyThirdPartyBaseModel(PolymorphicModel, ThirdPartyModel):
194 pass # or add fields
195
196 Or instead integrating the third party model anywhere into an
197 existing polymorphic inheritance tree:
198
199 .. code-block:: python
200
201 class MyBaseModel(SomePolymorphicModel):
202 my_field = models.CharField(max_length=10)
203
204 class MyModelWithThirdParty(MyBaseModel, ThirdPartyModel):
205 pass # or add fields
206
207
208 Non-Polymorphic Queries
209 -----------------------
210
211 If you insert :meth:`~polymorphic.managers.PolymorphicQuerySet.non_polymorphic` anywhere into the
212 query chain, then :pypi:`django-polymorphic` will simply leave out the final step of retrieving the
213 real objects, and the manager/queryset will return objects of the type of the base class you used
214 for the query, like vanilla Django would (``ModelA`` in this example).
215
216 .. code-block:: python
217
218 >>> qs=ModelA.objects.non_polymorphic().all()
219 >>> qs
220 [ <ModelA: id 1, field1 (CharField)>,
221 <ModelA: id 2, field1 (CharField)>,
222 <ModelA: id 3, field1 (CharField)> ]
223
224 There are no other changes in the behaviour of the queryset. For example,
225 enhancements for ``filter()`` or ``instance_of()`` etc. still work as expected.
226 If you do the final step yourself, you get the usual polymorphic result:
227
228 .. code-block:: python
229
230 >>> ModelA.objects.get_real_instances(qs)
231 [ <ModelA: id 1, field1 (CharField)>,
232 <ModelB: id 2, field1 (CharField), field2 (CharField)>,
233 <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]
234
235
236 About Queryset Methods
237 ----------------------
238
239 * :meth:`~django.db.models.query.QuerySet.annotate` and
240 :meth:`~django.db.models.query.QuerySet.aggregate` work just as usual, with the addition that
241 the ``ModelX___field`` syntax can be used for the keyword arguments (but not for the non-keyword
242 arguments).
243
244 * :meth:`~django.db.models.query.QuerySet.order_by` similarly supports the ``ModelX___field``
245 syntax for specifying ordering through a field in a submodel.
246
247 * :meth:`~django.db.models.query.QuerySet.distinct` works as expected. It only regards the fields
248 of the base class, but this should never make a difference.
249
250 * :meth:`~django.db.models.query.QuerySet.select_related` works just as usual, but it can not
251 (yet) be used to select relations in inherited models (like
252 ``ModelA.objects.select_related('ModelC___fieldxy')`` )
253
254 * :meth:`~django.db.models.query.QuerySet.extra` works as expected (it returns polymorphic
255 results) but currently has one restriction: The resulting objects are required to have a unique
256 primary key within the result set - otherwise an error is thrown (this case could be made to
257 work, however it may be mostly unneeded).. The keyword-argument "polymorphic" is no longer
258 supported. You can get back the old non-polymorphic behaviour by using
259 ``ModelA.objects.non_polymorphic().extra(...)``.
260
261 * :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances` allows you to turn a
262 queryset or list of base model objects efficiently into the real objects.
263 For example, you could do ``base_objects_queryset=ModelA.extra(...).non_polymorphic()``
264 and then call ``real_objects=base_objects_queryset.get_real_instances()``. Or alternatively
265 ``real_objects=ModelA.objects.get_real_instances(base_objects_queryset_or_object_list)``
266
267 * :meth:`~django.db.models.query.QuerySet.values` &
268 :meth:`~django.db.models.query.QuerySet.values_list` currently do not return polymorphic
269 results. This may change in the future however. If you want to use these methods now, it's best
270 if you use ``Model.base_objects.values...`` as this is guaranteed to not change.
271
272 * :meth:`~django.db.models.query.QuerySet.defer` and :meth:`~django.db.models.query.QuerySet.only`
273 work as expected. On Django 1.5+ they support the ``ModelX___field`` syntax, but on Django 1.4
274 it is only possible to pass fields on the base model into these methods.
275
276
277 Using enhanced Q-objects in any Places
278 --------------------------------------
279
280 The queryset enhancements (e.g. :meth:`~polymorphic.managers.PolymorphicQuerySet.instance_of`)
281 only work as arguments to the member functions of a polymorphic queryset. Occasionally it may
282 be useful to be able to use Q objects with these enhancements in other places. As Django doesn't
283 understand these enhanced Q objects, you need to transform them manually into normal Q objects
284 before you can feed them to a Django queryset or function:
285
286 .. code-block:: python
287
288 normal_q_object = ModelA.translate_polymorphic_Q_object( Q(instance_of=Model2B) )
289
290 This function cannot be used at model creation time however (in models.py), as it may need to access
291 the ContentTypes database table.
292
293
294 Nicely Displaying Polymorphic Querysets
295 ---------------------------------------
296
297 In order to get the output as seen in all examples here, you need to use the
298 :class:`~polymorphic.showfields.ShowFieldType` class mixin:
299
300 .. code-block:: python
301
302 from polymorphic.models import PolymorphicModel
303 from polymorphic.showfields import ShowFieldType
304
305 class ModelA(ShowFieldType, PolymorphicModel):
306 field1 = models.CharField(max_length=10)
307
308 You may also use :class:`~polymorphic.showfields.ShowFieldContent` or
309 :class:`~polymorphic.showfields.ShowFieldTypeAndContent` to display additional information when
310 printing querysets (or converting them to text).
311
312 When showing field contents, they will be truncated to 20 characters. You can modify this behavior
313 by setting a class variable in your model like this:
314
315 .. code-block:: python
316
317 class ModelA(ShowFieldType, PolymorphicModel):
318 polymorphic_showfield_max_field_width = 20
319 ...
320
321 Similarly, pre-V1.0 output formatting can be re-estated by using
322 ``polymorphic_showfield_old_format = True``.
323
324
325 Create Children from Parents (Downcasting)
326 ------------------------------------------
327
328 You can create an instance of a subclass from an existing instance of a superclass using the
329 :meth:`~polymorphic.managers.PolymorphicManager.create_from_super` method
330 of the subclass's manager. For example:
331
332 .. code-block:: python
333
334 super_instance = ModelA.objects.get(id=1)
335 sub_instance = ModelB.objects.create_from_super(super_instance, field2='value2')
336
337 The restriction is that ``super_instance`` must be an instance of the direct superclass of
338 ``ModelB``, and any required fields of ``ModelB`` must be provided as keyword arguments. If multiple
339 levels of subclassing are involved, you must call this method multiple times to "promote" each
340 level.
341
342 Delete Children, Leaving Parents (Upcasting)
343 --------------------------------------------
344
345 The reverse operation of :meth:`~polymorphic.managers.PolymorphicManager.create_from_super` is to
346 delete the subclass instance while keeping the superclass instance. This can be done using the
347 ``keep_parents=True`` argument to :meth:`~django.db.models.Model.delete`. :pypi:`django-polymorphic`
348 ensures that the ``polymorphic_ctype`` fields of the superclass instances are updated accordingly
349 when doing this.
350
351 .. _restrictions:
352
353 Restrictions & Caveats
354 ----------------------
355
356 * Database Performance regarding concrete Model inheritance in general. Please see
357 :ref:`performance`.
358
359 * Queryset methods :meth:`~django.db.models.query.QuerySet.values`,
360 :meth:`~django.db.models.query.QuerySet.values_list`, and
361 :meth:`~django.db.models.query.QuerySet.select_related` are not yet fully supported (see above).
362 :meth:`~django.db.models.query.QuerySet.extra` has one restriction: the resulting objects are
363 required to have a unique primary key within the result set.
364
365 * Diamond shaped inheritance: There seems to be a general problem with diamond shaped multiple
366 model inheritance with Django models (tested with V1.1 - V1.3). An example
367 `is here <http://code.djangoproject.com/ticket/10808>`_. This problem is aggravated when trying
368 to enhance :class:`~django.db.models.Model` by subclassing it instead of modifying Django core
369 (as we do here with :class:`~polymorphic.models.PolymorphicModel`).
370
371 * The enhanced filter-definitions/Q-objects only work as arguments for the methods of the
372 polymorphic querysets. Please see above for ``translate_polymorphic_Q_object``.
373
374 * When using the :django-admin:`dumpdata` management command on polymorphic tables
375 (or any table that has a reference to :class:`~django.contrib.contenttypes.models.ContentType`),
376 include the :option:`--natural-primary <dumpdata.--natural-primary>` and
377 :option:`--natural-foreign <dumpdata.--natural-foreign>` flags in the arguments.
378
379 * If the ``polymorphic_ctype_id`` on the base table points to the wrong
380 :class:`~django.contrib.contenttypes.models.ContentType` (this can happen if you delete child
381 rows manually with raw SQL, ``DELETE FROM table``), then polymorphic queries will elide the
382 corresponding model objects:
383
384 * ``BaseClass.objects.all()`` will **exclude** these rows (it filters for existing child
385 types).
386 * ``BaseClass.objects.non_polymorphic().all()`` will behave as normal - but polymorphic
387 behavior for the affected rows will be undefined - for instance,
388 :meth:`~polymorphic.managers.PolymorphicQuerySet.get_real_instances` will raise an
389 exception.
390
391 Always use ``instance.delete()`` or ``QuerySet.delete()`` to ensure cascading deletion of the
392 base row. If you must delete manually, ensure you also delete the corresponding row from the
393 base table.
394
395 * There will be problems if the :class:`~django.contrib.contenttypes.models.ContentType` cache
396 becomes out of sync with the database. This can especially happen in tests. You should ensure
397 that the cache is cleared (
398 :meth:`~django.contrib.contenttypes.models.ContentTypeManager.clear_cache`) whenever this
399 happens. In tests this happens when if :django-admin:`flush` is called by the teardown sequence
400 in :class:`~django.test.TransactionTestCase`.
401
402 .. old links:
403 - http://code.djangoproject.com/wiki/ModelInheritance
404 - http://lazypython.blogspot.com/2009/02/second-look-at-inheritance-and.html
405 - http://www.djangosnippets.org/snippets/1031/
406 - http://www.djangosnippets.org/snippets/1034/
407 - http://groups.google.com/group/django-developers/browse_frm/thread/7d40ad373ebfa912/a20fabc661b7035d?lnk=gst&q=model+inheritance+CORBA#a20fabc661b7035d
408 - http://groups.google.com/group/django-developers/browse_thread/thread/9bc2aaec0796f4e0/0b92971ffc0aa6f8?lnk=gst&q=inheritance#0b92971ffc0aa6f8
409 - http://groups.google.com/group/django-developers/browse_thread/thread/3947c594100c4adb/d8c0af3dacad412d?lnk=gst&q=inheritance#d8c0af3dacad412d
410 - http://groups.google.com/group/django-users/browse_thread/thread/52f72cffebb705e/b76c9d8c89a5574f
411 - http://peterbraden.co.uk/article/django-inheritance
412 - http://www.hopelessgeek.com/2009/11/25/a-hack-for-multi-table-inheritance-in-django
413 - http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name/929982#929982
414 - http://stackoverflow.com/questions/1581024/django-inheritance-how-to-have-one-method-for-all-subclasses
415 - http://groups.google.com/group/django-users/browse_thread/thread/cbdaf2273781ccab/e676a537d735d9ef?lnk=gst&q=polymorphic#e676a537d735d9ef
416 - http://groups.google.com/group/django-users/browse_thread/thread/52f72cffebb705e/bc18c18b2e83881e?lnk=gst&q=model+inheritance#bc18c18b2e83881e
417 - http://code.djangoproject.com/ticket/10808
418 - http://code.djangoproject.com/ticket/7270