Django:在这种情况下使用抽象基础模型是个好主意吗?
class Account(models.Model):
identifier = models.CharField(max_length=5)
objects = MyCustomManager()
class Meta:
abstract = True
class Customer(Account):
name = models.CharField(max_length=255)
如果我有很多模型,并且我想节省时间,不用到处放置外键,这样对吗?或者,我认为这一切都是错误的吗?
class Account(models.Model):
identifier = models.CharField(max_length=5)
objects = MyCustomManager()
class Meta:
abstract = True
class Customer(Account):
name = models.CharField(max_length=255)
If I have a lot of models, and I want to save time from having to put foreignkeys everywhere, is this right? Or, am I thinking of this all wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于外键的方向。您不能拥有抽象类的外键。
也许这是您感兴趣的通用关系或者抽象模型类中的外键< /a>.
尽管请注意,继承始终是一种
is-a
关系,而正常的外键使用则意味着一种has-a
关系。在您的示例中,
Customer
不应从Account
继承,因为客户拥有帐户。一个继承示例是一个地点,它可以是餐厅或电影院等。
评论后编辑:
,在 文档:
仅当继承的类在某种程度上属于同一范围时我才会这样做。
如果您确实拥有如此多的类,以至于向这些类添加一行很重要,那么您可能没有良好的数据库或应用程序设计。
并且尽量不要将所有内容都放在一个管理器中,以便能够在很多类中只使用一个管理器。
It depends in which direction the foreign keys go. You cannot have a foreign key to an abstract class.
Maybe it is Generic Relations what is interesting for you or foreign keys in abstract model classes.
Although notice that inheritance is always a
is-a
relationship while a normal foreign key usage implies ahas-a
relationship.In your example,
Customer
should not inherit fromAccount
as a customer has an account.An inheritance example would be a Place which is either a Restaurant or a Cinema etc.
Edit after comment:
Well, there is a own section for this in the documentation:
I would only do if the inherited classes belong somehow to the same scope.
If you really a so many classes that it matters to add one line to these classes then you probably have not a good DB or application design.
And try not to put everything in one manager just to be able to use only one manager in a lot classes.
在这种情况下,您将拥有 1 个包含帐户 ID 的客户表,如果您添加工作人员,他将拥有自己的包含帐户 ID 的表。
我想你可能想要一个包含帐户和附加对象客户、工人等的单表?这样您就永远不会混淆您的帐户。
In this case you'll have 1 table for customer with account ID and if you'll add Worker he'll have his own table with account ID.
I think you probably want to have single table with accounts and attached objects customers, workers etc? This way you'll never mix-up your accounts.