inheritance - Determining Django Model Instance Types after a Query on a Base-class -


is there way determine 'real' class of django database object is, after has been returned query on base class?

for instance, if have these models...

class animal(models.model):     name= models.charfield(max_length=128)  class person(animal):     pants_size = models.integerfield(null=true)  class dog(animal):     panting_rate = models.integerfield(null=true) 

and create these instances...

person(name='dave').save() dog(name='mr. rufflesworth').save() 

if query animal.objects.all(), end 2 animal instances, not instance of person , instance of dog. there way determine instance of type?


fyi: tried doing this...

isinstance(animal.objects.get(name='dave'),person) # <-- returns false! 

but doesn't seem work.

i had similar problem in past , found satisfactory solution this answer.

by implementing abstract class stores real class , have inherited parent class, once can cast each parent class instance actual type. (the abstract class used in answer available in django-model-utils.)

for example, once have abstract class defined (or if have django-model-utils), can do:

class animal(inheritancecastmodel):     name= models.charfield(max_length=128)  class person(animal):     pants_size = models.integerfield(null=true)  class dog(animal):     panting_rate = models.integerfield(null=true) 

using trivial:

>>> zoo.models import animal, person, dog >>> animal(name='malcolm').save() >>> person(name='dave').save() >>> dog(name='mr. rufflesworth').save() >>> obj in animal.objects.all(): ...     print obj.name, type(obj.cast()) ... malcolm <class 'zoo.models.animal'> dave <class 'zoo.models.person'> mr. rufflesworth <class 'zoo.models.dog'> 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -