简体   繁体   English

django-使用外键进行多表继承

[英]django - Use foreign key for multi-table inheritance

I am stuck in an odd position in my database design, and I would appreciate some comments. 我在数据库设计中处于一个奇怪的位置,我希望能提出一些意见。 We are using django-shop for an e-commerce platform. 我们正在将django-shop用于电子商务平台。 There is a base class defined for products: 为产品定义了一个基类:

from polymorphic.polymorphic_model import PolymorphicModel

class BaseProduct(PolymorphicModel):
    ...
    class Meta:
        abstract = True

We extended this base class for our own Product object: 我们将此基本类扩展为我们自己的Product对象:

class Product(BaseProduct):
    # custom fields

We now want to create another object, representing an offer to this Product object, something like: 现在,我们要创建另一个对象,以表示该Product对象的报价,例如:

class Offer(models.Model):
    product = models.ForeignKey(Product)
    # more

We want this Offer object to be added to the cart, and used in orders, just like the regular Product class. 我们希望将此Offer对象添加到购物车,并在订单中使用,就像常规Product类一样。 Yet, Cart and Order classes expects objects of type Product 但是, CartOrder类期望使用Product类型的对象

class Order(models.Model):
    product = models.ForeignKey(Product)

So as it is, we can't add Offer objects to the cart, or save them in orders. 因此,我们不能将Offer对象添加到购物车中,也不能将它们保存在订单中。

I was thinking of making Offer a subclass of Product as well, but instead of having a OneToOne relationship used in typical multi-table inheritance, somehow change it to a regular ForeignKey. 我当时也在考虑将Offer设为Product的子类,但不是在典型的多表继承中使用OneToOne关系,而是以某种方式将其更改为常规的ForeignKey。 I'm not even sure if this makes sense, let alone be possible. 我什至不确定这是否有意义,更不用说可能了。

Our database is already deployed in production with many Product objects, and this offer class is something we want to add on top, without modifying the rest. 我们的数据库已经在生产中部署了许多Product对象,并且此offer类是我们想要添加的东西,而无需修改其余部分。

Any thoughts on how to approach this? 关于如何解决这个问题有什么想法吗?

Use Model Inheritance 使用模型继承

class Offer(Product):

    products = ManyToManyField(Product, related_name='offers')

This will create an offer (which is also a product, and hence can be added to a cart) which also points at a number of related products. 这将创建一个要约(这也是一个产品,因此可以添加到购物车中),该要约还指向许多相关产品。

Instead of "Adding an offer to the cart", why not use django-shop-discounts ? 为什么不使用django-shop-discounts而不是“在购物车中添加要约”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM