DavidL
DavidL

Reputation: 1260

Django - Find out which model the variable belongs to

If I pass a variable as an argument, Can I find out which model it belongs to?

For example, if there is some_model, can I find out if it belongs to model Pizza or Toppings, etc?

Upvotes: 3

Views: 1409

Answers (3)

Jordan
Jordan

Reputation: 2039

For if statements this worked for me

from app.models import SomeModel
model_var = SomeModel()
if type(model_var) == SomeModel:
    #Do stuff
    pass

Upvotes: 0

Ilya
Ilya

Reputation: 1399

Test if some_model is of type inherited from MyType

issubclass(type(some_model), MyType)

Test if some_model is instance of MyType

isinstance(some_model, MyType)

Upvotes: 8

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Passing an object to type() will tell you the type of the object.

print type(some_model) 

Upvotes: 5

Related Questions