views:

52

answers:

1

I have a rather generic model, as follows:

class Keyword(models.Model):
    ancestors = models.ManyToManyField(Keyword)
    name = models.CharField()
    description = models.CharField()

Trouble is, I have several different types of keywords, which all have different forms of business logic. Some, for example, are never allowed to have any ancestors. Others can never be ancestors.

It gets more complicated, but the base question is this: I can create a flat class and possibly use a type enum, but then I'm not sure how I would enforce that, for example, ancestors can only be of a certain type. Or I could create a hierarchy of classes, but then I wouldn't be able to do something like models.ManyToManyField(Keyword), because I'd need to include multiple types.

I think I can work around this dilemma, but it's messy and doesn't look at all like clean business logic. Any suggestions on doing it nicely?

+1  A: 

I think you're describing single-table inheritance. It is not currently supported in Django.

Out of supported options I recommend using Proxy models and enforce class-specific constraints through validation in overloaded save() methods of subclasses.

Alex Lebedev