3

I'm tring to use select_related on multi-table inheritance lookup.
My code has some drawbacks and wonder if there are better solution

class Parent(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL)


class Child(models.Model):

    pass

With the above class definition, I'd like to serialize parents (heterogeneous)

parents = Parent.objects.all().select_related('user', 'child')

for parent in parents:
    parent.child.user           # <-- another db access, nullifies select_related('user')
    # i'm passing parent.child to ChildSerializer() which expects child object, and it access the user, so it's parent.child.user

I can do

Parent.objects.all().selecte_related('child__user')

but it has its own problem when there are multiple child models (it needs join for each child class)

eugene
  • 39,839
  • 68
  • 255
  • 489

0 Answers0