Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object in child class from object in parent class in django

Let's say I have a parent class (ThingsThatMigrate) and two children (Coconut and Swallow). Now let's say I have a ThingsThatMigrate object. How can I determine if it is in fact a Coconut or a Swallow? Once having done so, how can I get to the Coconut or Swallow object?

like image 699
jMyles Avatar asked Mar 18 '11 04:03

jMyles


2 Answers

Django doesn't offer such model polymorphism out of the box.The easiest way to do what you are trying to achieve is to store the content type of a new object in it. There's a simple generic app called django-polymorphic-models which offers you this functionality - and - additionally a downcast-method that will return the child object!

like image 134
Bernhard Vallant Avatar answered Dec 04 '22 05:12

Bernhard Vallant


Concrete or abstract inheritance? If concrete:

>>> things = ThingsThatMigrate.objects.all().select_related('coconut', 'swallow')
>>> for thing in things:
...     thing = thing.coconut or thing.swallow or thing
...     print thing

This can be automated using django-model-utils InheritanceManager (then you don't need to worry about select_related or manually listing all possible subclasses). Maintained by another Django core developer.

like image 25
DrMeers Avatar answered Dec 04 '22 05:12

DrMeers