Django access to subclasses items from abstract class

前端 未结 2 1736
眼角桃花
眼角桃花 2021-02-16 00:05
class Animal(models.Model):
    ....
    class Meta:
        abstract = True

class Cat(models.Model, Animal):
    ...

class Dog(models.Model, Animal):
    ....
         


        
相关标签:
2条回答
  • 2021-02-16 00:21

    You might be interested in django_polymorphic

    Example from project docs:

    When we store models that inherit from a Project model...

    >>> Project.objects.create(topic="Department Party")
    >>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner")
    >>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")
    

    ...and want to retrieve all our projects, the subclassed models are returned:

    >>> Project.objects.all()
    [ <Project:         id 1, topic "Department Party">,
      <ArtProject:      id 2, topic "Painting with Tim", artist "T. Turner">,
      <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]
    
    0 讨论(0)
  • 2021-02-16 00:42

    This is not possible in one query. You have two options, one use to use django-model-utils or you can use django_polymorphic.

    Polymorphic is better suited to your task, however django-model-utils is made by a very prominent member of the django community and as such has a lot of good support.

    If I had to choose, I'd choose django-model-utils since its made by a member of the django team, and thus will be supported. Polymorphic is supported by divio, which is a private company that heavily uses django based in Switzerland.

    As for how to select Sub-classes. You need to do two things using django-model-utils. Firstly, you need to change the objects variable in your model to InheritanceManager() like so (adapted from docs):

    from model_utils.managers import InheritanceManager
    
    class Place(models.Model):
        # ...
        objects = InheritanceManager()
    
    class Restaurant(Place):
        # ...
    
    class Bar(Place):
        # ...
    
    nearby_places = Place.objects.filter(location='here').select_subclasses()
    for place in nearby_places:
        # "place" will automatically be an instance of Place, Restaurant, or Bar
    

    The code above will return all Bars and Restaurants because it uses the select_subclasses.

    0 讨论(0)
提交回复
热议问题