Django模型可以有两个抽象类吗?
我有这个模型:
class BillHeader(models.Model):
billno = models.IntegerField(primary_key=True, blank=True)
class BillData(models.Model):
price = models.DecimalField(_('Price'), max_digits=12, decimal_places=2)
amount = models.DecimalField(_('Amount'), max_digits=6, decimal_places=2)
[... rest of the model ...]
class Meta:
abstract = True
class BillFooter(models.Model):
total = models.DecimalField(_('Total'), max_digits=12, decimal_places=2)
[... rest of the model ...]
class Meta:
abstract = True
BillData
和 BillFooter
对于每个 BillHeader
是通用的,因此我将它们标记为抽象
.我可以做 BillHeader(BillData,BillFooter)类
还是做错了什么?
BillData
and BillFooter
are common to every BillHeader
so I've marked them as abstract
. Can I do class BillHeader(BillData, BillFooter)
or I'm doing something wrong?
我还考虑过要主要制作 BillData
和 BillHeader
BillFooter
抽象.我没有做数据模型的经验(至少不是复杂的模型),我有点迷茫.你会推荐什么?
I also thought about doing BillData
the main one, and BillHeader
BillFooter
abstract. I don't have any experience on doing data models (at least not complex ones) and I'm a bit lost. What would you recommend?
是的,只要不导致模棱两可的模型解析顺序",Django模型就可以从任意多个抽象基类中继承..将继承视为一条链...您从其继承的每个类都是链中的一个链接.从两个基类继承只是在链中添加两个链接,而不是一个.
Yes, a Django model can inherit from as many abstract base classes as you like, as long as they don't result in an ambiguous "model resolution order". Think of inheritance as a chain... each class you inherit from is a link in the chain. Inheriting from two base classes is just adding two links to the chain instead of one.
换句话说,如果您的抽象基类继承自 models.Model
,则不要尝试同时继承抽象基类和 models
. Bill
类中的.Model models.Model
已经在继承链中,因此从其继承会在基类链中造成混乱.
In other words, if your abstract base classes inherit from models.Model
, then don't try to inherit from both the abstract base class and models.Model
in your Bill
class. models.Model
is already in the inheritance chain, so inheriting from it causes chaos in the chain of base classes.
关于 I 如何构造这些类,我将创建一个名为 Bill
的模型,该模型继承自 BillHeader
, BillData
和 BillFooter
.原因是我喜欢Django模型来代表离散的对象(例如Bill,Article,BlogPost,Photo等)
As to how I would structure these classes, I would create a model called Bill
that inherited from BillHeader
, BillData
, and BillFooter
. The reason for this is that I like my Django models to represent discrete objects (e.g. Bill, Article, BlogPost, Photo, etc.)
但是,抽象基类的要点是能够为公共字段和方法添加一定程度的抽象,以便多个类可以从它们继承.如果您只是创建Bill类,那么它就毫无意义.但是,如果您有Bill,UnpaidBill和PaidBill ...所有这些都将具有应该出现在所有字段上的公共字段,那么您可以通过抽象到ABC来避免很多麻烦.
However, the point of abstract base classes is to be able to add a level of abstraction to common fields and methods so that multiple classes can inherit from them. If you're just creating a Bill class it's somewhat meaningless. If, however, you had Bill, and UnpaidBill, and PaidBill... all of those would have common fields that should appear on all of them and you can save yourself a lot of trouble by abstracting to an ABC.
希望这为ABC和继承的优点提供了一些见识.
Hopefully that offers a little insight to what ABC's and inheritance are good for.