How to get all instances inherited from the same parent class in django

I have two models that inherit from the same abstract base class.

I expect that I can get all instances from classes that are children of the base class, with something like AbstractClass.objects.all ()

Of course, I could join inquiries for all children, but it is terrible, and it ceases to work if I add a new class for children.

Is this possible with Django ORM? What will be the elegant solution?

+3
source share
1 answer

django, , . , . . ORM, .

:

class NotQuiteAbstractBaseClass(models.Model):
    def get_specific_subclass(self):
        if self.model1:
            return self.model1
        elif self.model2:
            return self.model2
        else:
            raise RuntimeError("Unknown subclass")

class Model1(NotQuiteAbstractBaseClass):
    def whoami(self):
        return "I am a model1"

class Model2(NotQuiteAbstractBaseClass):
    def whoami(self):
        return "I am a model2"

:

for obj in NotQuiteAbstractBaseClass.objects.iterator():
    obj = obj.get_specific_subclass()
    print obj.whoami()
+1

Source: https://habr.com/ru/post/1727449/


All Articles