代码之家  ›  专栏  ›  技术社区  ›  Donovan Keating

Django模型:\uu str\uuuuu,具有外部对象的名称

  •  1
  • Donovan Keating  · 技术社区  · 8 年前

    所以我有一个 Product ProductImage 型号。每个 产品 可以有多个 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*>
    

    如果产品图像是手机的图像,比如iPhone X,那么图像应该是这样显示的。现在,“产品图像”列仅显示 ProductImage公司 对象。如何解决此问题? enter image description here

    2 回复  |  直到 8 年前
        1
  •  3
  •   Lemayzeur    8 年前

    试试这个。

    提示:代替 product_id 字段名称可以是 product

    如果您更改名称 product\u id 产品 ,请记住product\u id,如下所示

    def __str__(self):
        return "%s %s" % (self.product_id.name, self.product_id.id )
    
        2
  •  0
  •   user9754369 user9754369    8 年前

    理想情况下,您应该有 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公司 将引发错误。