Opened 14 years ago
Closed 14 years ago
#14371 closed (worksforme)
Select related and parents
Reported by: | Vlastimil Zíma | 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: | no | UI/UX: | no |
Description
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.
Example:
class Parent(models.Model) pass 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
Note:
See TracTickets
for help on using tickets.
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():