From 5f180216409d75290478c71ddb0ff8a68c91dc16 Mon Sep 17 00:00:00 2001 From: Johannes Westphal Date: Sat, 30 Mar 2024 22:14:15 +0000 Subject: [PATCH] Fixed #35344, Refs #34838 -- Corrected output_field of resolved columns for GeneratedFields in aliased tables. Thanks Simon Charette for the review. --- AUTHORS | 1 + django/db/models/fields/generated.py | 2 +- docs/releases/5.0.4.txt | 3 +++ tests/model_fields/test_generatedfield.py | 14 ++++++++++++-- 4 files changed, 17 insertions(+), 3 deletions(-) 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")