开发者

Django models - many classes vs few classes? Working with "not-exactly-inheritance" relationships

开发者 https://www.devze.com 2022-12-09 20:00 出处:网络
I have a rather generic model, as follows: class Keyword(models.Model): ancestors = models.ManyToManyField(Keyword)

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 dile开发者_运维百科mma, but it's messy and doesn't look at all like clean business logic. Any suggestions on doing it nicely?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号