简体   繁体   English

模型冗余Django表?

[英]Model redundant django tables?

I am working to figure out the model for a Django project: an app to track Books . 我正在努力找出Django项目的模型:一个用于跟踪Books的应用程序。

Among other fields, every Book has either/both a Printer and a Publisher , which are basically identical. 在其他领域中,每本书都具有PrinterPublisher ,两者基本相同。 So, here's how it stands: 因此,它是这样的:

class Book(models.Model):
    title     = models.CharField(max_length=100)
    printer   = models.ForeignKey('Printer')
    publisher = models.ForeignKey('Publisher')

class Printer(models.Model):
    name      = models.CharField(max_length=100)
    location  = models.CharField(max_length=100)

class Publisher(models.Model):
    name      = models.CharField(max_length=100)
    location  = models.CharField(max_length=100)

It seems to me this is bad database form: it's not DRY. 在我看来,这是不好的数据库形式:它不是DRY。 In addition, quite often, a Book might be printed by a firm which publishes the same or another book: in other words, the tables can overlap. 另外,很多时候,一Book可能由出版同一本书或另一本书的公司印刷:换句话说,表格可以重叠。 So, the two models Printer and Publisher should really be combined, while they need to remain distinct in the admin. 因此,“ Printer和“ Publisher者”这两个模型应该真正结合在一起,而在管理中则需要保持区别。

My question: how best to do this? 我的问题:如何最好地做到这一点? Should I create another model, Firm , and create one-to-one relationships between it and Printer / Publisher ? 我是否应该创建另一个模型Firm ,并在它与Printer / Publisher之间建立一对一的关系?

The Django way to handle that is to create an Abstract Base Model . Django处理的方法是创建一个Abstract Base Model This is the DRY way to create your models. 这是创建模型的DRY方法。 Here is the code: 这是代码:

class BaseModel(models.Model):
    name      = models.CharField(max_length=100)
    location  = models.CharField(max_length=100)

    class Meta:
        abstract = True

class Printer(BaseModel):
    pass

class Publisher(BaseModel):
    pass

This will allow you to specify redundant fields only once. 这将使您只能指定一次冗余字段。 Also, if you need to add any extra fields to one model, just add them instead of using pass . 此外,如果您需要向一个模型添加任何其他字段,只需添加它们而不是使用pass

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

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