Search code examples
djangoinheritancepython-object

(django) get query of child class


I have a super class like this:

class Superclass(models.Model):
 number = models.PositiveIntegerField()

 class Meta:
  abstract = True

 def get_next(self):
  return Superclass.objects.get(number=self.number+1)

Now, I have a child class that inherits from the superclass.

What's the problem?

  1. I can't do this: Superclass.objects because the superclass doesn't refer to any database table.
  2. I don't want to query all Superclass childs, only the one of the current child class, like this: When I do instance_of_child1.get_next I don't want to get an instance of Child2.

How to solve this?

  • My first idea was to add a static constant to any child class that contains the class (So I could do self.myclass.objects) But this seems to be not a good way.
  • Make the method get_next being part of the child class. Problem: there will be duplicates.

Solution

  • This should work:

    def get_next(self):
        return self.__class__.objects.get(number=self.number+1)