views:

272

answers:

1

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.

+4  A: 

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.

Daniel Roseman
Thanks Daniel. I had been looking at contenttypes and generic relations yesterday, but it didn't really click. Im going to try it out now and see if it solves the issue.
Sandro