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

dannyroa picture dannyroa · Feb 23, 2010 · Viewed 15.7k times · Source

I have a class called BankAccount as base class. I also have CheckingAccount and SavingsAccount classes that inherit from BankAccount.

BankAccount is not an abstract class but I do not create an object from it, only the inheriting classes.

Then, I execute a query like this:

account = BankAccount.objects.get(id=10)

How do I know if account is CheckingAccount or SavingsAccount?

The way I do this now is in this way:

checking_account = CheckingAccount.objects.get(id=account.id)

If it exists, it is a CheckingAccount, otherwise, it is a SavingsAccount.

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Feb 23, 2010

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