这是我的django模型
因为我有ProjectsArchive
和StatusArchive
来保存历史数据
你可以看到很多字段都是重复的
我想知道如何减少重复代码以使代码简单
class Projects(models.Model):
title = models.CharField(max_length=255, blank=True)
link = models.CharField(max_length=300, blank=True)
state = models.CharField(max_length=30, blank=True)
update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
....
class ProjectsArchive(models.Model):
title = models.CharField(max_length=255, blank=True)
link = models.CharField(max_length=300, blank=True)
state = models.CharField(max_length=30, blank=True)
update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
....
class Status(models.Model):
project = models.ForeignKey(Projects, null = True, blank = True)
state = models.CharField(max_length=255, blank=True)
crawl_update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
....
class StatusArchive(models.Model):
project = models.ForeignKey(ProjectsArchive, null = True, blank = True)
state = models.CharField(max_length=255, blank=True)
crawl_update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
....
答案 0 :(得分:2)
您可以在此处参考:Abstract base classes
根据你的问题,我会这样做:
class BasicInfo(models.Model):
title = models.CharField(max_length=255, blank=True)
link = models.CharField(max_length=300, blank=True)
state = models.CharField(max_length=30, blank=True)
update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
class Meta:
abstract = True
class Projects(BasicInfo):
....
class ProjectsArchive(BasicInfo):
....
完成BasicInfo
后,您可以重复使用title
,link
,state
和update_at
。
但是,我们可以为state
和crawl_update_at
创建包含Status
和StatusArchive
的通用模型。
class StatusInfo(models.Model):
state = models.CharField(max_length=255, blank=True)
crawl_update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
class Meta:
abstract = True
class Status(StatusInfo):
project = models.ForeignKey(Projects, null = True, blank = True)
....
class StatusArchive(StatusInfo):
project = models.ForeignKey(ProjectsArchive, null = True, blank = True)
...
答案 1 :(得分:0)
您可以创建一个CommonModel,您可以在其中放置冗余字段,然后在继承CommonModel而不是models.Model的情况下使用您想要使用它们的模型。
class CommonModel(models.Model):
class Meta:
abstract = True
title = models.CharField(max_length=255, blank=True)
link = models.CharField(max_length=300, blank=True)
state = models.CharField(max_length=30, blank=True)
update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
class ProjectArchive(CommonModel):
any_new_field_you_want_to_add
答案 2 :(得分:0)
您正在寻找的是抽象元课程。
https://docs.djangoproject.com/en/1.8/topics/db/models/
class ProjectTemplate(models.Model):
title = models.CharField(max_length=255, blank=True)
link = models.CharField(max_length=300, blank=True)
state = models.CharField(max_length=30, blank=True)
update_at = models.DateTimeField(auto_now=True, blank=True, null=True)
....
class Meta:
abstract = True
class Projects(ProjectTemplate):
pass
class ProjectsArchive(ProjectTemplate):
pass
答案 3 :(得分:0)