Opened 3 weeks ago

Last modified 3 weeks ago

#37389 assigned Bug

AlterField on parent PK can generate SQL for unmanaged child model

Reported by: Felix Engelmann Owned by: Felix Engelmann
Component: Migrations Version: 5.2
Severity: Normal Keywords: unmanaged, inheritance, MTI
Cc: Felix Engelmann Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The main issue was applying old migrations of models that inherit but are unmanaged. A prime example is a database view that extends a real model, both in terms of python functions and with database columns.

The model.py is as follows:

from django.db import models

class Parent(models.Model):
    name = models.CharField()

class Child(Parent):
    class Meta:
        managed = False

The main culprit happened, when the DEFAULT_AUTO_FIELD setting changed e.g. from django.db.models.AutoField to BigAutoField. This lead makemigrations to create an operation:

migrations.AlterField(
            model_name='parent',
            name='id',
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),

This migration in the current code tried to follow the parent_ptr OneToOne relation and update the foreign key in the Child table. As Child is a view, this failed on postgres.
The proposed fix is to exclude unmanaged models in the _is_relevant_relation function to make old migrations run.

This migration works well in django 3.

Change History (2)

comment:1 by Jacob Walls, 3 weeks ago

Keywords: MTI added
Owner: set to Felix Engelmann
Patch needs improvement: set
Status: new → assigned
Summary: avoid changing relations from unmanaged models → AlterField on parent PK can generate SQL for unmanaged child model
Triage Stage: Unreviewed → Accepted
Version: 6.1 → 5.2

Thanks for the report, reproduced on 5.2.17.

I've just reopened the PR. Mind looking into the linter failures and then unsetting the "Needs Improvement" box here? Thanks.

comment:2 by Felix Engelmann, 3 weeks ago

Patch needs improvement: unset

I fixed the formatting and opened a new PR ​https://github.com/django/django/pull/22062

Note: See TracTickets for help on using tickets.
Back to Top