如何在Django中定义模型之间的多态关系? [英] How can I define a polymorphic relation between models in Django?
问题描述
我正在开发一个包含优惠
模型的Django应用程序。 优惠
实例包含定价条件并指向产品定义。产品模型实际上是一个层次结构(我有一个电视
模型,一个摄像机
模型等)。所以我希望提供
模型包含多态(或通用)关联以指向任何产品。
I am working on a Django application which contains an Offer
model. An Offer
instance contains the pricing conditions and points to a product definition. The product model is actually a hierarchy (I have a Television
model, a Camcorder
model, etc.). So I would like the Offer
model to contain a polymorphic (or "generic") association to point to any product.
现在,我发现这是使用通用 ContentTypes
应用程序中的关联。这可能是,但我正在寻找替代品,如果有的话。
For now, all I have found is this to use the generic associations in the ContentTypes
application. This might do, but I am looking for alternatives, if any.
感谢您的帮助。
一个解决方案请回答)
推荐答案
ContentTypes是正确的方法。
这是因为ForignKey只能指向一种类型的表,所以您需要通过一个中间表,并根据不同的类型进行拆分。
ContentTypes is the right approach. This is because the ForignKey can only point to one type of table so you need to pass through the an intermediate table and do your split depending on the different type.
所以类层次结构的模型继承,但外键的ContentType。
So model inheritance for the class hierarchy, but ContentType for the foreign keys.
这篇关于如何在Django中定义模型之间的多态关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!