我们有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。从BigMethods继承BigFields。从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):
passinheritance?中的
发布于 2012-03-23 18:43:23
如果您的模型中有这样的顺序字段,那么解决方案不是继承,而是将这些字段分解成一个单独的模型,并创建一对多的关系。很难用您的示例模型来说明问题,所以我将使用我正在进行的项目中的一个模型。
最初的模型如下所示:
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'https://stackoverflow.com/questions/9843581
复制相似问题