Django型号:外物名称为

2024-09-25 16:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个ProductProductImage模型。每个Product可以有多个ProductImage模型。在Django管理页面中,我希望产品图片显示与之相关的产品的名称。在

class Product(models.Model):
    name = models.CharField(max_length=150)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    product_count = models.IntegerField(blank=True, default=0)
    description = models.TextField()



class ProductImage(models.Model):
    image_addr = models.FileField(upload_to='products/')
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)

    def __str__(self):
        q = <*name of the product with the product_id*>

如果一个产品图像是一部手机的图像,比如iphonex,图像应该是这样显示的。现在,product images列只显示ProductImage对象。我怎么解决这个问题? enter image description here


Tags: thedjangoname模型图像idmodel产品
2条回答

试试这个。在

TIP: instead of product_id the field name could be product

如果您将名称product_id更改为product,请记住下面的产品标识

def __str__(self):
    return "%s %s" % (self.product_id.name, self.product_id.id )

理想情况下,每个模型中都应该有一个unicode方法,这样您就可以以更具描述性的方式查看数据。你的模特应该喜欢这个

class Product(models.Model):
    name = models.CharField(max_length=150)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    product_count = models.IntegerField(blank=True, default=0)
    description = models.TextField()

    def __unicode__(self):
        return u"{}-{}".format(self.id, self.name)

class ProductImage(models.Model):
    image_addr = models.FileField(upload_to='products/')
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)    

    def __unicode__(self):
        return u"{}".format(self.product_id)

这里我建议unicode而不是str,因为如果产品名称包含非ascii字符,则str将引发错误。在

相关问题 更多 >