开发者

ManyToMany relationship between inherited model and its parent

Probably easiest to explain with an example:

class Item(models.Model):
    # ...

class ComplexItem(Item):
    components = models.ManyToManyField(Item, through='ComponentItem', sym开发者_C百科metrical=False, related_name='component_of')

class ComponentItem(models.Model):
    # ...
    item = models.ForeignKey(ComplexItem)
    component = models.ForeignKey(Item, related_name='used_in_items

I would like a table of Items, with a name, price etc. Then I would like to define ComplexItems which are Items in their own right, but they require other Items in varying quantities.

The above causes the following exception in the admin app:

<class 'inventory.models.ComponentItem'> has more than 1 ForeignKey to <class 'inventory.models.ComplexItem'>

I need to override instance methods in ComplexItem and generally seperate the behavior from Item and the inheritance makes sense from a pure data view.

Is there some alternative definition of this relationship? I'd also like to avoid needing 'related_name' on both ComponentItem.component and ComplexItem.components.


You need to go back to the drawing board. While it's probably technically possible for a model to both inherit from and simultaneously be composed of another model, it's going to get sticky quick.

Try making ComplexItem just inherit from models.Model like Item does. Bet you that change alone will fix everything.


The model above actually works fine (I think, I haven't tested and decided against it for the moment). However the table generated for ComplexItem only has one column pointing to Item, which is fairly useless.

The functionality of ComponentItem can still be gotten by defining a ManyToMany relationship from Item to 'self' through ComponentItem.

Defining separate behavior is as easy as creating a Proxy model.

The actual error above came from my admin.Inline not being able to pick the correct foreign key to use for a ComponentItem, which can be solved like this.

I may come back to the inheritance above, but this works for now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜