我有以下型号:
# carts/models.py
class Cart(models.Model):
# Used to determine card type when inheriting. See example.
content_type = models.ForeignKey(ContentType)
class SingleProductCart(Cart):
"""Regular cart with single product."""
@property
def product(self):
pass
# orders/models.py
class Order(models.Model):
# Has to work with any Cart subclass.
cart = models.ForeignKey(to='carts.Cart')
因此,我遇到了以下代码:
def do_something_with_single_product_order(order):
# We assume there that order.cart is a SingleProductCart instance.
assert order.content_type.model_class() == SingleProductCart # True
do_something_with_product(order.cart.product) # Attribute error.
哪个引发异常,因为order.cart
属性引用了Cart模型实例
而不是SingleProductCart,并且没有属性product
。
如何在没有额外的数据库查询的情况下将Cart模型实例投射到SingleProductCart或如何组织模型以使它们返回正确类的对象?