I have:
class Foo(models.Model):
pass
class Bar(Foo):
pass
class Corn(Foo):
pass
# Now I have these objects in the database:
john = Corn()
mary = Corn()
joe = Bar()
grace = Corn()
randy = Bar()
In Django, I use this to get a list of Foo objects:
foos = Foo.objects.all()
Now, how do I check if an object in foos list above is a Bar or a Corn?
for x in foos:
print x.__class__.__name__ # returns Foo
Model inheritance won’t automatically return the subclass instances — if you ask the ORM for Foos, it will give you Foos. You need to ask if there is a Bar object with the same primary key:
You can also use the model name (in lowercase) as an attribute, which will do the lookup for you, but it’s not guaranteed to succeed (obviously), so you need to guard against DoesNotExist exceptions: