简体   繁体   English

重用Django模型

[英]Reusing django models

I have an app with a bunch of models and templates to perform a certain task (it's called a "user access review", but that's not important - the app is called "uar"). 我有一个带有一堆模型和模板的应用程序,可以执行某些任务(这被称为“用户访问审查”,但这并不重要-该应用程序被称为“ uar”)。 When the users have completed their task, we want to archive the data from the main models into what we're calling "history" tables. 用户完成任务后,我们希望将主要模型中的数据存档到我们所谓的“历史”表中。 Those tables are identical in structure to the original "uar" tables, but may live in another database or may be in the same database. 这些表在结构上与原始“ uar”表相同,但可以存在于另一个数据库中,也可以位于同一数据库中。 They will, however, be read-only except by the process that archives them into these history tables, and possibly a task that expires items after a certain number of years. 但是,它们将是只读的,除非通过将它们存档到这些历史表中的过程以及可能会使某项在一定年后到期的任务完成。

Since I wanted the exact same model structure but different names, I thought I'd just make an app called "uar_history" and symlink the models.py file between the two apps. 由于我想要完全相同的模型结构但名称不同,因此我想只制作一个名为“ uar_history”的应用程序,然后在两个应用程序之间符号链接models.py文件。 But when I attempt to syncdb the new models, I get a lot of complaints about the models not validating because of the related_name back link on the foreign keys. 但是当我尝试syncdb新模型时,由于外键上的related_name反向链接,我收到很多关于模型无法验证的抱怨。

Is there a better approach to this? 有更好的方法吗? Should I just make all my archive tables sub-classes of the model classes instead? 我是否应该将所有存档表的子类都设为模型类的子类?

@Brandon gave the right answer, you should use a common abstract model for the shared definition. @Brandon给出了正确的答案,您应该为共享定义使用通用的抽象模型。 They can be in the same file or separate model files (I chose common , current , and history as the apps for this example): 它们可以在同一文件中,也可以在单独的模型文件中(在此示例中,我选择commoncurrenthistory作为应用程序):

common/models.py 通用/ models.py

class CommonPostModel(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()

    class Meta:
        abstract = True

current/models.py 电流/ models.py

class CurrentPostModel(CommonPostModel):
    pass

history/models.py 历史/ models.py

class ArchivePostModel(CommonPostModel):
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM