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

后端 未结 6 1803
春和景丽
春和景丽 2021-01-02 17:46

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

6条回答
  •  误落风尘
    2021-01-02 18:08

    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.

提交回复
热议问题