Access the superclass of a Django Model

2019-07-29 06:54发布

问题:

Given a Django Model

class Sub(models.Model):
    name = models.CharField(max_length=100)
    size_in_inches = models.IntegerField(default=6)

class TunaSub(Sub):
    fish_ingredient = models.CharField(max_length=10, default="Tuna")

class MeatballSub(Sub):
    meat_ingredient = models.CharField(max_length=20, default="Meatball with Cheese")

I would like to access the attribute of the superclass for, say a __str__ method (in Python 3.x). How can I do so? Is this the correct solution?

class TunaSub(Sub):
    fish_ingredient = models.CharField(max_length=10, default="Tuna")
    def __str__(self):
        return self.super().name

class MeatballSub(Sub):
    meat_ingredient = models.CharField(max_length=20, default="Meatball with Cheese")
    def __str__(self):
        return self.super().name

回答1:

Since you extend Sub, name is also a field of both TunaSub and MeatballSub. So you can simply use

def __str__(self):
    return self.name

As a side note, since you are extending a concrete model, you are in fact creating three separate tables in the database (named sub, tuna_sub, and meatball_sub) which are connected via one-to-one relations. If you only want to reuse the field definitions in sub and not actually create a table for it, use an abstract base model class.