|
| 1 | +# Generated manually to backfill polymorphic_ctype on existing items. |
| 2 | +from django.db import migrations |
| 3 | + |
| 4 | + |
| 5 | +def populate_polymorphic_ctypes(apps, schema_editor): |
| 6 | + Item = apps.get_model("a4modules", "Item") |
| 7 | + ContentType = apps.get_model("contenttypes", "ContentType") |
| 8 | + db_alias = schema_editor.connection.alias |
| 9 | + |
| 10 | + def get_parent_link(model): |
| 11 | + for field in model._meta.fields: |
| 12 | + remote_field = getattr(field, "remote_field", None) |
| 13 | + if remote_field and remote_field.parent_link: |
| 14 | + return field |
| 15 | + return None |
| 16 | + |
| 17 | + # Update all known subclasses first. |
| 18 | + for model in apps.get_models(): |
| 19 | + if model is Item: |
| 20 | + continue |
| 21 | + try: |
| 22 | + is_item_subclass = issubclass(model, Item) |
| 23 | + except TypeError: |
| 24 | + continue |
| 25 | + if not is_item_subclass: |
| 26 | + continue |
| 27 | + |
| 28 | + parent_link_field = get_parent_link(model) |
| 29 | + if not parent_link_field: |
| 30 | + continue |
| 31 | + |
| 32 | + content_type = ContentType.objects.db_manager(db_alias).get_for_model( |
| 33 | + model, for_concrete_model=False |
| 34 | + ) |
| 35 | + item_ids = model._default_manager.using(db_alias).values_list( |
| 36 | + parent_link_field.attname, flat=True |
| 37 | + ) |
| 38 | + ( |
| 39 | + Item.objects.using(db_alias) |
| 40 | + .filter(polymorphic_ctype__isnull=True, pk__in=item_ids) |
| 41 | + .update(polymorphic_ctype=content_type) |
| 42 | + ) |
| 43 | + |
| 44 | + # Any remaining items fallback to the base Item content type. |
| 45 | + base_ct = ContentType.objects.db_manager(db_alias).get_for_model( |
| 46 | + Item, for_concrete_model=False |
| 47 | + ) |
| 48 | + ( |
| 49 | + Item.objects.using(db_alias) |
| 50 | + .filter(polymorphic_ctype__isnull=True) |
| 51 | + .update(polymorphic_ctype=base_ct) |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def remove_polymorphic_ctypes(apps, schema_editor): |
| 56 | + Item = apps.get_model("a4modules", "Item") |
| 57 | + Item.objects.using(schema_editor.connection.alias).update(polymorphic_ctype=None) |
| 58 | + |
| 59 | + |
| 60 | +class Migration(migrations.Migration): |
| 61 | + dependencies = [ |
| 62 | + ("a4modules", "0009_alter_item_options_item_polymorphic_ctype"), |
| 63 | + ] |
| 64 | + |
| 65 | + operations = [ |
| 66 | + migrations.RunPython( |
| 67 | + populate_polymorphic_ctypes, reverse_code=remove_polymorphic_ctypes |
| 68 | + ), |
| 69 | + ] |
0 commit comments