简体   繁体   中英

Abstract base class inheritance in Django with foreignkey

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).

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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