On Jun 1, 5:39 am, Rex <rex.eastbou...@gmail.com> wrote: > Hello, > > I have a question that is best illustrated by the following fictional > example. (I put my question at the end.) > > #========= > # In models.py > class Room(models.Model): > animal = models.ForeignKey(Animal) > > class Animal(models.Model): > #[...] > > class Duck(Animal): > #[...] > > # In views.py > my_duck = Duck() > #[...] > > my_room = Room(animal=my_duck) > #[...] > > # QUESTION: What should the following expression return? > isinstance(my_room.animal, Duck) > #========= > > Django appears to return False. Accordingly, I get an error when I try > to call the quack() method on my_room.animal, since that method is > defined for Ducks but not for Animals. I am running into a situation > where I would like to call the quack() method if the room's animal is > an instance of Duck. Is there some way to do this? > > Regards, > > Rex
This is a reasonably frequently asked question. As the documentation points out, if you ask Django for an instance of the parent class, that's what you'll get. There's no way to get from that to the derived class, as the database doesn't record that information. So the best thing to do is to have an 'animal_type' field on your parent class, which is set automatically on save to whatever type the child class is - then you could have a method on the parent class which returns the actual object. -- DR. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---