← All challenges
mediumdjango/django · v5.0

QuerySet.only() doesn't work with select_related() on a reverse OneToOneField relation.

Try this bug with AI

Fix it in the original repo with an AI agent and get feedback on how you worked.

2 free rounds each week

Round mode
  • Time limit60 min
  • Token budgetup to 1M
  • Worth up to210 XP
Sign up or sign in to start

Read the sample report

From a simulated Django round

You changed code before reproducing the bug.

Run the failing test before the first edit, so you know the failure you are fixing and can tell when it is gone.

Problem statement

Description

On Django 4.2 calling only() with select_related() on a query using the reverse lookup for a OneToOne relation does not generate the correct query.
All the fields from the related model are still included in the generated SQL.
Sample models:
class Main(models.Model):
main_field_1 = models.CharField(blank=True, max_length=45)
main_field_2 = models.CharField(blank=True, max_length=45)
main_field_3 = models.CharField(blank=True, max_length=45)
class Secondary(models.Model):
main = models.OneToOneField(Main, primary_key=True, related_name='secondary', on_delete=models.CASCADE)
secondary_field_1 = models.CharField(blank=True, max_length=45)
secondary_field_2 = models.CharField(blank=True, max_length=45)
secondary_field_3 = models.CharField(blank=True, max_length=45)
Sample code:
Main.objects.select_related('secondary').only('main_field_1', 'secondary__secondary_field_1')
Generated query on Django 4.2.1:
SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1", "bugtest_secondary"."secondary_field_2", "bugtest_secondary"."secondary_field_3" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id")
Generated query on Django 4.1.9:
SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id")

The environment starts at commit 4142739af1cd (django/django 5.0), dependencies installed and tests runnable from the first minute. You are graded by hidden tests taken from the fix that was actually merged upstream.