显示外键值

我的 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}


繁花不似锦
浏览 57回答 1
1回答

临摹微笑

您可以使用hasattr检查您item是否需要 OneToOneFieldclass 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python