Django中的抽象基类继承与外键 [英] Abstract base class inheritance in Django with foreignkey

查看:129
本文介绍了Django中的抽象基类继承与外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django动力网站上继承模型,以坚持DRY。我的目标是使用一个名为BasicCompany的抽象基类来提供三个子类的常见信息:屠夫,贝克,烛台(他们位于他们自己的应用程序中,各自的名字)。

I am attempting model inheritance on my Django powered site in order to adhere to 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).

每个子类都需要一个可变数量的东西,如电子邮件地址,电话号码,URL等等,数量从0开始。所以我想要这些课程和他们所指的公司之间的一对一/ ForeignKey关系。这大概是我想象的BasicCompany / models.py看起来像:

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. So I want a many-to-one/ForeignKey relationship between these classes and the company they refer to. Here is roughly what I imagine BasicCompany/models.py looking like:

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.

我不知道该怎么做是将EmailAddress,URL,PhoneNumbers(etc)小孩班可以做到吗,如果是,怎么办?如果没有,我将不胜感激您对解决方法的建议。

What I don't know how to do is inherit EmailAddress, URLs, PhoneNumbers (etc) into the child classes. Can it be done, and if so, how? If not, I would appreciate your advice on workarounds.

推荐答案

我怀疑你会更好,通用关系链接,而不是试图将所有内容都绑定到基类。通用关系允许您将一个模型(如EmailAddress)链接到任何其他类,这似乎与您的用例非常吻合。

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.

这篇关于Django中的抽象基类继承与外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆