Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 690
dannyroa Avatar asked Feb 22 '10 23:02

dannyroa


People also ask

How do you check if a class is subclass of another class in Python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False .

How do I check if an object is an instance of a given class or of a subclass of it?

The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).

What class does a Django model class inherit?

The basics: Each model is a Python class that subclasses django. db. models.

What is the class of instance object in Django?

The two main concepts of OOP are classes and objects: Class: Class is basically a blueprint or a template for creating objects. Object: Collection of arguments and methods which can be performed on those data. An object is nothing but an instance of the class.


1 Answers

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

like image 135
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 19:09

Ignacio Vazquez-Abrams