访问Django模型的超类 [英] Access the superclass of a Django Model
问题描述
给出Django模型
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")
我想访问超类的属性,例如 __ str __
方法(在Python 3中)。 X)。我该怎么办?这是正确的解决方案吗?
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
推荐答案
由于您扩展了 Sub
,因此名称
也是 TunaSub
和 MeatballSub
的字段。因此,您可以简单地使用
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
作为补充说明,由于要扩展具体模型,因此实际上是在数据库中创建三个单独的表(名为 sub
, tuna_sub
和 meatball_sub
)通过以下方式连接:一对一的关系。如果只想重用 sub
中的字段定义,而不是真正为其创建表,请使用抽象基础模型类。
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.
这篇关于访问Django模型的超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!