简体   繁体   中英

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. 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:

class Product(BaseProduct):
    # custom fields

We now want to create another object, representing an offer to this Product object, something like:

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. Yet, Cart and Order classes expects objects of type 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.

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. 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.

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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