1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

[5.0.x] Fixed #35359 -- Fixed migration operations ordering when adding fields referenced by GeneratedField.expression.

Thank you to Simon Charette for the review.

Backport of 9aeb38c296 from main.
This commit is contained in:
DevilsAutumn
2024-04-12 20:01:41 +05:30
committed by Natalia
parent fa202d5cb1
commit 24f54c3b09
4 changed files with 146 additions and 1 deletions

View File

@@ -1035,6 +1035,8 @@ class MigrationAutodetector:
self.to_state,
)
)
if field.generated:
dependencies.extend(self._get_dependencies_for_generated_field(field))
# You can't just add NOT NULL fields with no default or fields
# which don't allow empty strings as default.
time_fields = (models.DateField, models.DateTimeField, models.TimeField)
@@ -1435,6 +1437,20 @@ class MigrationAutodetector:
dependencies.append((through_app_label, through_object_name, None, True))
return dependencies
def _get_dependencies_for_generated_field(self, field):
dependencies = []
referenced_base_fields = models.Q(field.expression).referenced_base_fields
newly_added_fields = sorted(self.new_field_keys - self.old_field_keys)
for app_label, model_name, added_field_name in newly_added_fields:
added_field = self.to_state.models[app_label, model_name].get_field(
added_field_name
)
if (
added_field.remote_field and added_field.remote_field.model
) or added_field.name in referenced_base_fields:
dependencies.append((app_label, model_name, added_field.name, True))
return dependencies
def _get_dependencies_for_model(self, app_label, model_name):
"""Return foreign key dependencies of the given model."""
dependencies = []