Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model Inheritance - get child

Tags:

django

Is there a way to access the actual child of the base model, means: Staying with the example from the django Docs, let's assume I am modeling different delivery restaurants, that just have in common

  • name
  • all have a deliver method

as of this:

class Place(models.Model):
    name = models.CharField(max_length=10)

class Pizzeria(Place):
    topping = models.CharField(max_length=10)
    tip = models.IntegerField()

    def deliver(self):
        deliver_with_topping(self.topping)
        ask_for_tip(self.tip)

class Shoarma(Place):
    sauce = models.CharField(max_length=10)
    meat = models.CharField(max_lenght=10)

    def deliver(self):
        prepare_sauce_with_meat(self.sauce, self.meat)

I would now like to execute:

Place.objects.get(name="my_place").<GENERIC_CHILD>.deliver()

i.e. I don't need to know what the place is actually, just the common deliver method. The model then 'knows' what to call.

Is there something like <GENERIC_CHILD>?

like image 587
ProfHase85 Avatar asked Nov 07 '22 13:11

ProfHase85


1 Answers

I always use Inheritance Manager from django-model-utils for this kind of operations. On your models:

class Place(models.Model):
    objects = InheritanceManager()   #<- add inheritance manager
    name = models.CharField(max_length=10)

    def deliver(self):
        pass  #not needed

Your query:

Place.objects.get_subclass(name="my_place").deliver() 

For me it is a clean and elegant solution. Don't forget to star-up django-model-util repo if you like it.

like image 155
dani herrera Avatar answered Nov 15 '22 06:11

dani herrera