I have the following model structure:
class A(models.Model):
prop_a = models.CharField(max_length=255)
class B(A):
prop_b = models.CharField(max_length=255)
class C(A):
prop_c = models.CharField(max_length=255)
class D(models.Model):
fk = models.ForeignKey('A')
So essentially, I have a model (D) which has a foreign key to an 'abstract' model (A) which is subclassed by B and C.
Now, when I run D.objects.all().select_related(), only the properties of Aare queried. I assume this is because at query time, Django does not know which child class the fk is an instance of (and neither do I in my current structure).
Is there any way to query the properties of the child class without changing the model structure?
I also tried prefetch_related and tried using an InheritanceManager from django-model-utils, both to no avail.
Edit: To clarify, I am looking for a way to iterate over objects of D, accessing the concrete values of fk (which are either B or C objects) while only hitting the database once.
Running D.objects.all().select_related() produces the query
'SELECT "mapping_d"."id", "mapping_d"."fk_id", "mapping_a"."id", "mapping_a"."prop_a" FROM "mapping_d" INNER JOIN "mapping_a" ON ("mapping_d"."fk_id" = "mapping_a"."id")'
Let's say one of those is an object d of type D whose property fk is of type C.
Now, when I access the value d.fk.c, Django runs an additional query to get the properties of C:
'SELECT "mapping_a"."id", "mapping_a"."prop_a", "mapping_c"."a_ptr_id", "mapping_c"."prop_c" FROM "mapping_c" INNER JOIN "mapping_a" ON ("mapping_c"."a_ptr_id" = "mapping_a"."id") WHERE "mapping_c"."a_ptr_id" = 3'
I want to avoid this additional query per object of D. Using an InheritanceManager in the proposed way does not seem to do that.