﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34321	Unexpected query result after call QuerySet.only() to ForeignKey() with 'self' reference	Mahardhika Praja	nobody	"Unexpected query result after calling `QuerySet.only('ref__field')` to `ForeignKey('self')`

{{{#!python
class MyModel(models.Model):
    f1 = models.IntegerField()
    f2 = models.IntegerField()
    f3 = models.IntegerField()
    ref = models.ForeignKey(""self"", on_delete=models.CASCADE)

print(str(MyModel.objects.select_related('ref').only('ref__f1').query))
}}}

Output
{{{
'SELECT ""mymodel"".""id"", ""mymodel"".""f1"", ""mymodel"".""ref_id"", T2.""id"", T2.""f1"", T2.""ref_id"" FROM ""mymodel"" INNER JOIN ""mymodel"" T2 ON (""mymodel"".""ref_id"" = T2.""id"")'
}}}

Fields `""mymodel"".""f2""` and `""mymodel"".""f3""` are excluded from column selection

Another try

{{{#!python
print(str(MyModel.objects.select_related('ref').only('f1', 'f2', 'f3', 'ref__f1').query))
}}}

Output
{{{
'SELECT ""mymodel"".""id"", ""mymodel"".""f1"", ""mymodel"".""f2"", ""mymodel"".""f3"", ""mymodel"".""ref_id"", T2.""id"", T2.""f1"", T2.""f2"", T2.""f3"", T2.""ref_id"" FROM ""mymodel"" INNER JOIN ""mymodel"" T2 ON (""mymodel"".""ref_id"" = T2.""id"")'
}}}

"	Bug	new	Database layer (models, ORM)	3.2	Normal		queryset		Unreviewed	0	0	0	0	0	0
