inheritance - django orm - How to use select_related() on the Foreign Key of a Subclass from its Super Class -
i've found django orm's handling of subclassing models pretty spiffy. that's why run problems one.
take 3 models:
class a(models.model): field1 = models.charfield(max_length=255) class b(a): fk_field = models.foreignkey('c') class c(models.model): field2 = models.charfield(max_length=255) so can query a model , b models, available:
the_as = a.objects.all() in the_as: print a.b.fk_field.field2 #note throws error if there no b record the problem looking @ huge number of database calls retrieve of data.
now suppose wanted retrieve queryset of a models in database, of subclass records , subclass's foreign key records well, using select_related() limit app single database call. write query this:
the_as = a.objects.select_related("b", "b__fk_field").all() one query returns of data needed! awesome.
except not. because version of query doing own filtering, though select_related not supposed filter results @ all:
set_1 = a.objects.select_related("b", "b__fk_field").all() #only returns objects associated b objects set_2 = a.objects.all() #returns objects len(set_1) > len(set_2) #will false i used django-debug-toolbar inspect query , found problem. generated sql query uses inner join join c table query, instead of left outer join other subclassed fields:
select "app_a"."field1", "app_b"."fk_field_id", "app_c"."field2" "app_a" left outer join "app_b" on ("app_a"."id" = "app_b"."a_ptr_id") inner join "app_c" on ("app_b"."fk_field_id" = "app_c"."id"); and seems if change inner join left outer join, records want, doesn't me when using django's orm.
is bug in select_related() in django's orm? there work around this, or going have direct query of database , map results myself? should using django-polymorphic this?
it looks bug, seems ignoring nullable nature of a->b relationship, if example had foreign key reference b in instead of subclassing, foreign key of course nullable , django use left join it. should raise in django issue tracker. try using prefetch_related instead of select_related might around issue.
Comments
Post a Comment