How can I determine if instance of class from Djan

2019-03-15 15:01发布

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.

5条回答
小情绪 Triste *
2楼-- · 2019-03-15 15:19

A little janky, but this would work:

>>> class BankAccount(object): pass
...
>>> class SavingsAccount(BankAccount): pass
...
>>> class CheckingAccount(BankAccount): pass
...
>>> x = SavingsAccount()
>>> type(x) == type(SavingsAccount())
True
>>> type(x) == type(CheckingAccount())
False
查看更多
趁早两清
3楼-- · 2019-03-15 15:26

After some more searching I found solutions akin to this: Django multi-table inheritance, how to know which is the child class of a model?

Basically, there's no elegant solution for this. You have to do a bunch of try-except statements and force django to use the class you want.

查看更多
霸刀☆藐视天下
4楼-- · 2019-03-15 15:32

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.

查看更多
\"骚年 ilove
5楼-- · 2019-03-15 15:41

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

查看更多
冷血范
6楼-- · 2019-03-15 15:42

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.

查看更多
登录 后发表回答