diff --git a/AUTHORS b/AUTHORS index a9cddfd4b1..4fb830afb6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -508,6 +508,7 @@ answer newbie questions, and generally made Django that much better: Joe Topjian Johan C. Stöver Johann Queuniet + Johannes Westphal john@calixto.net John D'Agostino John D'Ambrosio diff --git a/django/db/models/fields/generated.py b/django/db/models/fields/generated.py index 257feeeba2..5b6b188df0 100644 --- a/django/db/models/fields/generated.py +++ b/django/db/models/fields/generated.py @@ -39,7 +39,7 @@ class GeneratedField(Field): return Col(self.model._meta.db_table, self, self.output_field) def get_col(self, alias, output_field=None): - if alias != self.model._meta.db_table and output_field is None: + if alias != self.model._meta.db_table and output_field in (None, self): output_field = self.output_field return super().get_col(alias, output_field) diff --git a/docs/releases/5.0.4.txt b/docs/releases/5.0.4.txt index 6503f1ada3..6872d5998a 100644 --- a/docs/releases/5.0.4.txt +++ b/docs/releases/5.0.4.txt @@ -21,3 +21,6 @@ Bugfixes * Fixed a bug in Django 5.0 that caused a migration crash on PostgreSQL 15+ when adding a partial ``UniqueConstraint`` with ``nulls_distinct`` (:ticket:`35329`). + +* Fixed a crash in Django 5.0 when performing queries involving table aliases + and lookups on a ``GeneratedField`` of the aliased table (:ticket:`35344`). diff --git a/tests/model_fields/test_generatedfield.py b/tests/model_fields/test_generatedfield.py index a636e984fd..641ce591e4 100644 --- a/tests/model_fields/test_generatedfield.py +++ b/tests/model_fields/test_generatedfield.py @@ -123,7 +123,12 @@ class BaseGeneratedFieldTests(SimpleTestCase): db_persist=True, ) - col = Square._meta.get_field("area").get_col("alias") + field = Square._meta.get_field("area") + + col = field.get_col("alias") + self.assertIsInstance(col.output_field, IntegerField) + + col = field.get_col("alias", field) self.assertIsInstance(col.output_field, IntegerField) class FloatSquare(Model): @@ -134,7 +139,12 @@ class BaseGeneratedFieldTests(SimpleTestCase): output_field=FloatField(), ) - col = FloatSquare._meta.get_field("area").get_col("alias") + field = FloatSquare._meta.get_field("area") + + col = field.get_col("alias") + self.assertIsInstance(col.output_field, FloatField) + + col = field.get_col("alias", field) self.assertIsInstance(col.output_field, FloatField) @isolate_apps("model_fields")