Django-如何建立2个具有相同栏位的模型?

时间:2018-11-03 18:45:44

标签: django postgresql

我有一个具有20年销售历史的房地产应用程序。我想将最近两年的列表放入一个可以主动查询的模型中,将另外18年变成一个存档模型。

我在PostgreSQL 1.9.5和Django 1.11中使用

我有限的数据库管理知识告诉我这称为“水平分区”或“分片”。有没有在Django中进行设置的聪明方法?还是只复制相同的字段名称并将其粘贴到ListingActiveListingArchive中?

class ListingActive(models.Model):
    data1 = models.IntegerField()
    data2 = models.CharField(max_length=10)
    ...
    data100 = models.CharField(max_length=20)

class ListingArchived(models.Model):
    same fields as ListingActive

后续问题。我要同时执行水平分区垂直分区。

假设在每个Listing模型中,总共有100个字段,但是仅其中10个处于活动状态。其他90个字段是永远不会查询的显示详细信息。

最后,我希望总共显示以下4个模型。有什么方法可以使用抽象模型或其他方法进行设置?

class ListingActiveQuery(models.Model):
    actively_queried_data_1 = models.IntegerField()
    actively_queried_data_2 = models.IntegerField()
    ...
    actively_queried_data_10 = models.IntegerField()
    details = models.OneToOneField(ListingActiveDetails)

class ListingActiveDetails(models.Model):
    data_1 = models.IntegerField()
    data_2 = models.IntegerField()
    ...
    data_90 = models.IntegerField()

class ListingArchivedQuery(models.Model):
    actively_queried_data_1 = models.IntegerField()
    actively_queried_data_2 = models.IntegerField()
    ...
    actively_queried_data_10 = models.IntegerField()
    details = models.OneToOneField(ListingArchivedDetails)

class ListingArchivedDetails(models.Model):
    data_1 = models.IntegerField()
    data_2 = models.IntegerField()
    ...
    data_90 = models.IntegerField()

1 个答案:

答案 0 :(得分:3)

通常,您使用字段创建abstract model [Django-doc],然后将抽象模型子类化为两个真实模型。例如:

class AbstractDataModel(models.Model):
    data1 = models.IntegerField()
    data2 = models.CharField(max_length=10)
    # ...
    data100 = models.CharField(max_length=20)

    class Meta:
        abstract = True

class ListingActive(AbstractDataModel):
    pass

class ListingArchived(AbstractDataModel):
    pass

编辑

class AbstractQuery(models.Model):
    actively_queried_data_1 = models.IntegerField()
    actively_queried_data_2 = models.IntegerField()
    # ...
    actively_queried_data_10 = models.IntegerField()

    class Meta:
        abstract = True

class AbstractDetails(models.Model):
    data_1 = models.IntegerField()
    data_2 = models.IntegerField()
    # ...
    data_90 = models.IntegerField()

    class Meta:
        abstract = True

class ListingActiveQuery(AbstractQuery):
    details = models.OneToOneField(ListingActiveDetails)

class ListingActiveDetails(AbstractDetails):
    pass

class ListingArchivedQuery(AbstractQuery):
    details = models.OneToOneField(ListingArchivedDetails)

class ListingArchivedDetails(AbstractDetails):
    pass