philgo20
philgo20

Reputation: 6517

How do I get all instances that inherited from the same parent class in django

I have two models than inherited from the same abstract base class.

I would expect to be able to get all instances from classes that are children of the base class with something like AbstractClass.objects.all()

Of course I could join queries on all children but that's awful and it stops working if I add new children class.

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

Upvotes: 3

Views: 556

Answers (1)

Gattster
Gattster

Reputation: 4781

I have used django's other inheritance methods because I hit the same problem you are running into. I'm not sure if there is an elegant solution. Ultimately, you need several queries done on the DB and for the results to be merged together. I can't picture the ORM supporting that.

Here is my usual hackish approach for this situation:

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"

Then, you can query the entire list like this:

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

Upvotes: 1

Related Questions