我的 models.py 看起来像这样:class Order(models.Model): items = models.ManyToManyField(OrderItem)class OrderItem(models.Model): (item in the cart) item = models.ForeignKey(Item, on_delete=models.CASCADE)class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField()class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand = models.ManyToManyField(Brand) size = models.ManyToManyField(Size, blank=True)class Accessory(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand_accessory = models.ManyToManyField(BrandAccessory)所以目前item我OrderItem模型中的字段显示模型中项目的标题和数量Item:def __str__(self): return f"{self.quantity} of {self.item.title}"ItemOneToOneField与Bike和连接Accessory。是否可以显示品牌和尺寸,Bike如果它被添加到OrderItem,brand_accessory如果Accessory被添加到OrderItem?它看起来像 {quantity} {item.title}(如果是自行车)> {bike.brand} {bike.size}(如果附件)> {accessory.brand_accessory}
1 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
您可以使用hasattr检查您item
是否需要 OneToOneField
class OrderItem(models.Model):
...
def __str__(self):
if hasattr(self.item, 'bike'):
#get value you need like: self.item.bike.brand
if hasattr(self.item, 'accessory'):
#get value you need like: self.item.accessory.brand_accessory
return #get values you need together
添加回答
举报
0/150
提交
取消