继承人的Django模型成本

2024-10-01 04:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有django项目,我们发现有些模型变得巨大。在

class BigModel(models.Model):
    """
    Large set of fields
    """
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    ...
    fieldN = models.IntegerField()
    """
    Large set of methods
    """
    def method1(self): pass
    def method2(self): pass
    def method3(self): pass
    ...
    def methodN(self): pass

我想用方法列表将BigModel类分成更小的类。但在整个项目中,我们引用了BigModel类。在

所以我的想法是小步走:

  1. BigModel类划分为BigFields和{}。继承 BigMethods来自BigFields。从BigMethods继承BigModel。在
  2. 通过创建代理模型并在代码中用它们替换对BigModel的引用,减少{}类的大小。在

因此,在重构代码时,我们的代码如下所示:

^{pr2}$
  • 它将如何影响性能?在
  • python中一级继承的代价是什么?在
  • 元类会影响继承成本吗?在

Tags: of项目django代码模型selfmodelsdef
1条回答
网友
1楼 · 发布于 2024-10-01 04:58:28

如果您的模型中有这样的顺序字段,那么解决方案不是继承,而是将这些字段拆分为单独的模型并创建一对多关系。很难用您的示例模型来说明这一点,所以我将使用我正在从事的一个项目中的一个。在

最初的模型看起来像这样:

class Page(models.Model):
    title = models.CharField(max_length=256)
    section_1_title = models.CharField(max_length=256)
    section_1_content = models.TextField()
    section_2_title = models.CharField(max_length=256)
    section_2_content = models.TextField()
    section_3_title = models.CharField(max_length=256)
    section_3_content = models.TextField()
    ...

显然,这是一个需要维护的噩梦,因此我将其更改为以下内容:

^{pr2}$

相关问题 更多 >