Debian Codegraph @

docs/migrating.rst

raw
1 Migrating Existing Models
2 =========================
3
4 Existing models can be migrated to become polymorphic models. During migration, the
5 :attr:`~polymorphic.models.PolymorphicModel.polymorphic_ctype` field needs to be populated.
6
7 This can be done in the following steps:
8
9 #. Inherit your model from :class:`~polymorphic.models.PolymorphicModel`.
10 #. Create a Django migration file to create the ``polymorphic_ctype_id`` database column.
11 #. Make sure the proper :class:`~django.contrib.contenttypes.models.ContentType` value is filled in.
12
13 Filling the content type value
14 ------------------------------
15
16 The following code can be used to fill the value of a model:
17
18 .. code-block:: python
19
20 from django.contrib.contenttypes.models import ContentType
21 from myapp.models import MyModel
22
23 new_ct = ContentType.objects.get_for_model(MyModel)
24 MyModel.objects.filter(polymorphic_ctype__isnull=True).update(polymorphic_ctype=new_ct)
25
26 The creation and update of the ``polymorphic_ctype_id`` column can be included in a single Django
27 migration. For example:
28
29 .. code-block:: python
30
31 # -*- coding: utf-8 -*-
32 from django.db import migrations, models
33
34
35 def forwards_func(apps, schema_editor):
36 MyModel = apps.get_model('myapp', 'MyModel')
37 ContentType = apps.get_model('contenttypes', 'ContentType')
38
39 new_ct = ContentType.objects.get_for_model(MyModel)
40 MyModel.objects.filter(polymorphic_ctype__isnull=True).update(
41 polymorphic_ctype=new_ct
42 )
43
44
45 class Migration(migrations.Migration):
46
47 dependencies = [
48 ('contenttypes', '0001_initial'),
49 ('myapp', '0001_initial'),
50 ]
51
52 operations = [
53 migrations.AddField(
54 model_name='mymodel',
55 name='polymorphic_ctype',
56 field=models.ForeignKey(
57 related_name='polymorphic_myapp.mymodel_set+',
58 editable=False,
59 to='contenttypes.ContentType',
60 null=True
61 ),
62 ),
63 migrations.RunPython(forwards_func, migrations.RunPython.noop),
64 ]
65
66 It's recommended to let :django-admin:`makemigrations` create the migration file, and include the
67 :class:`~django.db.migrations.operations.RunPython` manually before running the migration.
68
69 .. versionadded:: 1.1
70
71 When the model is created elsewhere, you can also use the
72 :func:`~polymorphic.utils.reset_polymorphic_ctype` function:
73
74 .. code-block:: python
75
76 from polymorphic.utils import reset_polymorphic_ctype
77 from myapp.models import Base, Sub1, Sub2
78
79 reset_polymorphic_ctype(Base, Sub1, Sub2)
80
81 reset_polymorphic_ctype(Base, Sub1, Sub2, ignore_existing=True)