#34321 closed Bug (invalid)

Unexpected query result after call QuerySet.only() to ForeignKey() with 'self' reference

Reported by: Mahardhika Praja Owned by: nobody
Component: Database layer (models, ORM) Version: 3.2
Severity: Normal Keywords: queryset
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Mahardhika Praja)

Unexpected query result after calling QuerySet.only('ref__field') to ForeignKey('self')

class MyModel(models.Model):
    f1 = models.IntegerField()
    f2 = models.IntegerField()
    f3 = models.IntegerField()
    ref = models.ForeignKey("self", on_delete=models.CASCADE)



'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

print(str(MyModel.objects.select_related('ref').only('f1', 'f2', 'f3', 'ref__f1').query))


'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")'

Change History (2)

comment:1 by Mahardhika Praja, 18 months ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 18 months ago

Resolution: invalid
Status: newclosed

only() works as documented and expected, i.e. it replaces the set of fields to load immediately, so in your case all columns "mymodel"."f1", "mymodel"."f2", and "mymodel"."f3" from MyModel should be omitted in the SELECT clause. f1 appears because MyModel is involved more than once, it was fixed in b3db6c8dcb5145f7d45eff517bcd96460475c879 (see #21204).

Note: See TracTickets for help on using tickets.
Back to Top