我们有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
的{{1}}。从BigFields
继承BigModel
。BigMethods
的引用替换为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
答案 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'