diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 5448a2841b1..e9903a73b6f 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -959,9 +959,10 @@ class AutoField(Field): return value def get_prep_value(self, value): + from django.db.models.expressions import OuterRef value = super().get_prep_value(value) - if value is None: - return None + if value is None or isinstance(value, OuterRef): + return value return int(value) def contribute_to_class(self, cls, name, **kwargs): diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 2980d750c8b..561a8e3563d 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -530,6 +530,16 @@ class BasicExpressionsTests(TestCase): # This is a contrived example. It exercises the double OuterRef form. self.assertCountEqual(outer, [first, second, third]) + def test_nested_subquery_outer_ref_with_autofield(self): + first = Time.objects.create(time='09:00') + second = Time.objects.create(time='17:00') + SimulationRun.objects.create(start=first, end=second, midpoint='12:00') + inner = SimulationRun.objects.filter(start=OuterRef(OuterRef('pk'))).values('start') + middle = Time.objects.annotate(other=Subquery(inner)).values('other')[:1] + outer = Time.objects.annotate(other=Subquery(middle, output_field=models.IntegerField())) + # This exercises the double OuterRef form with AutoField as pk. + self.assertCountEqual(outer, [first, second]) + def test_annotations_within_subquery(self): Company.objects.filter(num_employees__lt=50).update(ceo=Employee.objects.get(firstname='Frank')) inner = Company.objects.filter(