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 23319 Django uses unnecessary join in concrete inheritance avidi nobody "In some situations django use JOIN to get data from parent model when it's unnecessary. == First case == Using select to get only fields of children. {{{ class Parent(models.Model): field_of_parent = models.TextField() class Child(Parent): field_of_child = models.TextField() }}} {{{ >>> str(Child.objects.only(""field_of_child"").all().query) 'SELECT ""homettt_child"".""parent_ptr_id"", ""homettt_child"".""field_of_child"" FROM ""homettt_child"" INNER JOIN ""homettt_parent"" ON ( ""homettt_child"".""parent_ptr_id"" = ""homettt_parent"".""id"" )' }}} == Second case == Get all fields but parent hasn't any field {{{ class EmptyParent(models.Model): pass class ChildB(EmptyParent): field_of_child = models.TextField() }}} {{{ >>> str(ChildB.objects.all().query) 'SELECT ""homettt_emptyparent"".""id"", ""homettt_childb"".""emptyparent_ptr_id"", ""homettt_childb"".""field_of_child"" FROM ""homettt_childb"" INNER JOIN ""homettt_emptyparent"" ON ( ""homettt_childb"".""emptyparent_ptr_id"" = ""homettt_emptyparent"".""id"" )' }}} == Third case == In similar way through relations: For example, ManyToMany relations django could use _ptr_id column to join but uses id column of parent. If you don't need any fields (or they don't exist) the join is unnecessary. {{{ class Parent(models.Model): field_of_parent = models.TextField() class Child(Parent): field_of_child = models.TextField() class OtherModel(models.Model): m2mrelation = models.ManyToManyField(Child) }}} {{{ other=OtherModel.objects.create() >>> other.m2mrelation.create() str(other.m2mrelation.only(""field_of_child"").all().query) >>> str(other.m2mrelation.only(""field_of_child"").all().query) 'SELECT ""homettt_child"".""parent_ptr_id"", ""homettt_child"".""field_of_child"" FROM ""homettt_child"" INNER JOIN ""homettt_othermodel_m2mrelation"" ON ( ""homettt_child"".""parent_ptr_id"" = ""homettt_othermodel_m2mrelation"".""child_id"" ) INNER JOIN ""homettt_parent"" ON ( ""homettt_child"".""parent_ptr_id"" = ""homettt_parent"".""id"" ) WHERE ""homettt_othermodel_m2mrelation"".""othermodel_id"" = 1' }}} Maybe these could be solved using _ptr_id as ""default pk"" in child models and only use id of parent if is necessary information of table's parent model. Tested in 1.7rc2 but maybe this appears in previous versions." Cleanup/optimization new Database layer (models, ORM) Normal Accepted 0 0 0 0 0 0