How can I determine if instance of class from Django model is subclass of another model?
Solution 1
Try to use the checkingaccount
and savingsaccount
attributes. The one it is will not blow up.
Solution 2
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.
Comments
-
dannyroa about 2 years
I have a class called
BankAccount
as base class. I also haveCheckingAccount
andSavingsAccount
classes that inherit fromBankAccount
.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
orSavingsAccount
?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 aSavingsAccount
.