With an instance of Concert I get: unbound method do_stuff() must be called with Concert instance as first argument (got ModelBase instance instead)
models.py:
class Event(models.Model):
def do_stuff(self):
response self.do_specific_stuff(self)
class Concert(Event):
def do_specific_stuff(self):
...
class Party(Event):
def do_specific_stuff(self):
...
views:
def index(request):
x = Concert.objects.get(name='Jack White @ Oakland')
output = x.do_stuff()
return HttpResponse(output)
My goal is to loop trough all the events and execute the do_specific_stuff child class method based on what kind of event it is.
In Django, inheritance triggers multi-table inheritance, but you don’t get the polymorphism in Python. It’s just an instance of the ORM not providing a perfect correspondence between the data schema and the object model.
In other words, when you query Event, you get back a whole bunch of Event objects, regardless of whether some of them are actually Concert or Party objects. You have to manually downcast. If an Event is a Concert, it will have an attribute called
concert, which points to the corresponding Concert subclass. Likewise for Party. If it is just a normal Event, it will have neither attribute.You could use the following property on Event to automatically downcast your object:
Then you could do something like:
Similar questions have come up before:
And this link has some other ideas: