[Python] How to handle existing data when introducing an intermediate model between a base...

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    Current models:

    class Task(PolymorphicModel):
    pass

    class DownloadTask(Task):
    pass


    New models: And now i want to do add a new layer called VirtualTask:

    class Task(PolymorphicModel):
    pass

    class VirtualTask(Task):
    pass

    class DownloadTask(VirtualTask):
    pass


    Migration it looks like this:

    class Migration(migrations.Migration):

    dependencies = [
    ("tasks", "0005_alter_task_last_error"),
    ]

    operations = [
    migrations.CreateModel(
    name="VirtualTask",
    fields=[
    (
    "task_ptr",
    models.OneToOneField(
    auto_created=True,
    on_delete=django.db.models.deletion.CASCADE,
    parent_link=True,
    primary_key=True,
    serialize=False,
    to="tasks.task",
    ),
    ),
    ],
    options={
    "abstract": False,
    "base_manager_name": "objects",
    },
    bases=("tasks.task",),
    ),
    migrations.RemoveField(
    model_name="downloadtask",
    name="task_ptr",
    ),
    migrations.AddField(
    model_name="downloadtask",
    name="virtualptask_ptr",
    field=models.OneToOneField(
    auto_created=True,
    default=1,
    on_delete=django.db.models.deletion.CASCADE,
    parent_link=True,
    primary_key=True,
    serialize=False,
    to="tasks.virtualtask",
    ),
    preserve_default=False,
    ),
    ]


    “How should I handle existing data when inserting a new intermediate model (VirtualTask) between a base model (Task) and its subclasses in Django

    • should I customize the migration file, and if so, what would be the step-by-step approach?”

    Continue reading...

Compartilhe esta Página