首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django模型-继承成本

Django模型-继承成本
EN

Stack Overflow用户
提问于 2012-03-23 17:15:49
回答 1查看 424关注 0票数 2

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

代码语言:javascript
复制
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继承BigFields。从BigMethods.
  2. By继承BigModel,创建代理模型并在代码中替换对BigModel的引用--减少BigMethods类的大小。

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

代码语言:javascript
复制
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

inheritance?中的

  • 是如何影响性能的?
  • 在python中的一级继承成本是多少?
  • 元类是否影响
  • 的成本?
EN

回答 1

Stack Overflow用户

发布于 2012-03-23 18:43:23

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

最初的模型如下所示:

代码语言:javascript
复制
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()
    ...

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

代码语言:javascript
复制
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'
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9843581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档