0

I.e. we have

class Place(models.Model):...
class Restaurant(Place):...
class Cafe(Place):...

I'd like to query Place somehow:

q = Place.objects.all() # how?

but for q[x] i'd like to have not Place class instance, but Restaurant or Cafe instead (what are really stored), so I'll be able to call some polymorphic methods of the models classes. Possible?

john.don83
  • 103
  • 1
  • 10

1 Answers1

1

You can only get instances of the parent class if you place your query on the parent class, but according to Django's documentation on Multi-table inheritance:

The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField).

You can therefore access Restaurant and Cafe instances through the restaurant and cafe related names:

for place in Place.objects.all():
    try:
        restaurant = place.restaurant
    except Restaurant.DoesNotExist:
        restaurant = None
    try:
        cafe = place.cafe
    except Cafe.DoesNotExist:
        cafe = None
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Yes, it's clear. The question is how to iterate over all possible child classes and through the whole inheritance chain. It's strange that there are no such mechanism, without polymorphism this kind of inheritance seems quite useless.. – john.don83 Aug 06 '18 at 10:14