Opened 13 minutes ago
#37573 assigned Bug
makemigrations generates unappliable AlterField operations for changed GeneratedFields
| Reported by: | Patel Namraa | Owned by: | Patel Namraa |
|---|---|---|---|
| Component: | Migrations | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Patel Namraa | Triage Stage: | Unreviewed |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
When an existing GeneratedField is modified, makemigrations generates an AlterField operation. However, applying the resulting migration with migrate raises a ValueError because modifying generated fields through AlterField is not supported.
This means that makemigrations can generate a migration that cannot be applied without manually editing the migration file.
For example, consider the following model:
from django.db import models
from django.db.models.functions import Upper
class Author(models.Model):
name = models.CharField(max_length=20)
upper_name = models.GeneratedField(
expression=Upper("name"),
output_field=models.CharField(),
db_persist=True,
)
Now change the generated field expression:
upper_name = models.GeneratedField(
expression=Lower("name"),
output_field=models.CharField(),
db_persist=True,
)
Running makemigrations generates an AlterField operation for upper_name.
However, running migrate fails with:
ValueError: Modifying GeneratedFields is not supported.
The same problem occurs when changing other database-relevant attributes of a generated field, such as output_field or db_persist, and when converting a regular field into a generated field or vice versa.
A workaround is to manually replace the generated AlterField operation with a RemoveField followed by an AddField, using the new field definition.
Expected behavior
Since generated fields cannot be modified using AlterField, the migration autodetector should generate a RemoveField followed by an AddField when a generated field is created, removed, or its database definition changes in a way that cannot be handled by AlterField.
Changes that do not require recreating the generated column, such as changes to non-database attributes, should continue to use AlterField where appropriate.
Proposed approach
The migration autodetector could detect changes to the generated-field definition and use the existing RemoveField and AddField generation mechanisms instead of generating an unsupported AlterField operation.
This would allow the generated column to be dropped and recreated with its updated definition, without requiring users to manually edit migration files.
The approach would also preserve the existing restriction that generated fields cannot be modified directly through AlterField, while making the migration autodetector generate operations that can actually be applied.