简体   繁体   English

使用foreignkey在Django中抽象基类继承

[英]Abstract base class inheritance in Django with foreignkey

I am attempting model inheritance on my Django powered site in order to adhere to DRY. 我正在我的Django供电网站上尝试模型继承,以便坚持DRY。 My goal is to use an abstract base class called BasicCompany to supply the common info for three child classes: Butcher, Baker, CandlestickMaker (they are located in their own apps under their respective names). 我的目标是使用一个名为BasicCompany的抽象基类来提供三个子类的公共信息:Butcher,Baker,CandlestickMaker(它们以各自的名称位于自己的应用程序中)。

Each of the child classes has a need for a variable number of things like email addresses, phone numbers, URLs, etc, ranging in number from 0 and up. 每个子类都需要可变数量的东西,如电子邮件地址,电话号码,URL等,数量从0到现在不等。 So I want a many-to-one/ForeignKey relationship between these classes and the company they refer to. 所以我希望这些类与他们引用的公司之间存在多对一/ ForeignKey关系。 Here is roughly what I imagine BasicCompany/models.py looking like: 这大概是我想象的BasicCompany / models.py看起来像:

from django.contrib.auth.models import User
from django.db import models

class BasicCompany(models.Models)
    owner = models.ForeignKey(User)
    name = models.CharField()
    street_address = models.CharField()
    #etc...

    class Meta:
        abstract = True

class EmailAddress(models.model)
    email = models.EmailField()
    basiccompany = models.ForeignKey(BasicCompany, related_name="email_addresses")

#etc for URLs,  PhoneNumbers, PaymentTypes.

What I don't know how to do is inherit EmailAddress, URLs, PhoneNumbers (etc) into the child classes. 我不知道怎么做是将EmailAddress,URL,PhoneNumbers(等)继承到子类中。 Can it be done, and if so, how? 可以这样做,如果是,怎么做? If not, I would appreciate your advice on workarounds. 如果没有,我将非常感谢您对解决方法的建议。

I suspect you'll be better off with generic relations for the links, rather than trying to tie everything to a base class. 我怀疑你会更好地使用链接的泛型关系 ,而不是试图将所有内容绑定到基类。 Generic relations allow you to link a model such as EmailAddress to any other class, which would seem to be a good fit with your use case. 通用关系允许您将诸如EmailAddress之类的模型链接到任何其他类,这似乎非常适合您的用例。

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

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