我们有django项目,我们发现有些模型变得巨大。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
类。
所以我的想法是采用简单的方法来做到这一点:
- 鸿沟
BigModel
类为BigFields
和BigMethods
。从BigFields
继承BigMethods
。从BigMethods
继承BigModel
。 - 通过创建代理模型并用代码替换对
BigModel
的引用 - 减小了BigMethods
类的大小。
因此,在重构我们的代码的那一刻将是这样的:
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中一级继承的成本是多少?
- 元类是否会影响继承的成本?
如果需要谈“字段N”那么是时候进一步规范化了。 – 2012-03-23 17:32:31
我认为method1,method2等仅仅是为了举例的目的,而不是他的领域/方法的真实姓名 – jterrace 2012-03-23 17:57:09
@jterrace:不*相当*我在... – 2012-03-23 18:46:44