Django模型 - 继承成本

时间:2012-03-23 17:15:49

标签: python django performance inheritance

我们有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课程分为BigFieldsBigMethods。继承 来自BigMethods的{​​{1}}。从BigFields继承BigModel
  2. 通过在代码中创建代理模型并将BigMethods的引用替换为BigModel - 减少BigMethods类的大小。
  3. 因此,在重构时我们的代码将如下所示:

    class BigFields(models.Model):
        class Meta:
            abstract = True
        """
        Large set of fields
        """
        field1 = models.IntegerField()
        field2 = models.IntegerField()
        field3 = models.IntegerField()
        ...
        fieldN = models.IntegerField()
    
    class BigMethods(BigFields):
        class Meta:
            abstract = True
        """
        Large set of methods
        """
        def method1(self): pass
        def method2(self): pass
        def method3(self): pass
        ...
        def methodN(self): pass
    
    class BigModel(BigMethods):
        pass
    
    • 它会如何影响性能?
    • python中一级继承的成本是多少?
    • 元类会影响继承成本吗?

1 个答案:

答案 0 :(得分:3)

如果在模型中有这样的连续字段,则解决方案不是继承,而是将这些字段分解为单独的模型并创建一对多关系。你的示例模型很难说清楚,所以我将使用我正在处理的项目中的一个。

原始模型看起来像这样:

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()
    ...

显然这是一个维持的噩梦,所以我将其更改为以下内容:

class Page(models.Model):
    title = models.CharField(max_length=256)

class Section(models.Model):
    page = models.ForeignKey(Page, related_name='sections')
    title = models.CharField(max_length=256)
    content = models.TextField()
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']
        order_with_respect_to = 'page'