How can I determine if instance of class from Django model is subclass of another model? How can I determine if instance of class from Django model is subclass of another model? django django

How can I determine if instance of class from Django model is subclass of another model?


Try to use the checkingaccount and savingsaccount attributes. The one it is will not blow up.


You could use isinstance(account, SavingsAccount), but is generally preferred to avoid it and use duck type inference by looking at the object's attributes, and see if it quacks like a subclass.

To see if an object has an attribute, you use the aptly named hasattr built-in function or use getattr and check for the raising of an AttributeError exception.


Add a GetAccountType() method to your Checking and Savings accounts, when you get the object back from BankAccount.objects.get() then call that, if everything that derives from BankAccount has that method then you'll be fine.