Opened 5 years ago

Closed 5 years ago

#14371 closed (worksforme)

Select related and parents

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


I have a parent model for multiple children, but has nothing but AutoField. I found out, that it is impossible to fill parent cache in queries.


class Parent(models.Model)

class Child(Parent)
  some_int = models.IntegerField()
>>> Child.objects.get(pk = 3).__dict__
{'_state': <django.db.models.base.ModelState object at 0x8eb19ac>,
 'id': 3,
 'some_int': 0,
 'parent_ptr_id': 3}

>>> Child.objects.select_related('parent').get(pk = 3).__dict__
{'_state': <django.db.models.base.ModelState object at 0x8eb19ac>,
 'id': 3,
 'some_int': 0,
 'parent_ptr_id': 3}

This also causes senseless SQLs when reaching parent from child (child.parent_ptr):

SELECT "myapp_parent"."id" FROM "myapp_parent" WHERE "myapp_parent"."id" = 3;

So far only workaround I found is:

child = Parent.objects.select_related('child').get(pk = 3).child

Change History (1)

comment:1 Changed 5 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

The select_related() isn't necessary -- the parent object is retrieved when the child object is retrieved, and is populated in the object cache. If you inspect the SQL generated by Child.objects.all():

SELECT `myapp_parent`.`id`, `myapp_child`.`parent_ptr_id`, `myapp_child`.`some_int` FROM `myapp_child` INNER JOIN `myapp_parent` ON (`myapp_child`.`parent_ptr_id` = `myapp_parent`.`id`)
Note: See TracTickets for help on using tickets.
Back to Top