我想在我的模型值(管理员)中显示来自外键的值。在Django Admin中显示来自外键的值
我使用的是“除了”我是我应该明确使用。我如何使用它?以及如何让下面的工作正确?它只是显示(无),但那里有价值。
感谢
Admin.py
----------------------
def price(self, obj):
try:
price = Price.objects.filter(variation=Variation.objects.filter(product=obj)[0])
except:
price = 'None'
return format_html('<center><b>"{0}"</b></center>', price.price)
Models.py
--------
class Product(models.Model):
name = models.CharField ("Name", max_length=130)
link = models.URLField("Link", max_length=740)
class Variation(models.Model):
product = models.ForeignKey(Product, blank=False, null=False)
variation = models.CharField (max_length=80, blank=True, null=True)
def __str__(self):
return self.variation
class Price(models.Model):
price = models.DecimalField("Price", decimal_places=2, max_digits=10)
variation = models.ForeignKey(Variation, blank=False, null=False)
updated = models.DateTimeField(auto_now=True)
def __int__(self):
return self.price
不应该是:''回报format_html( '
您应该知道Django ORM为ForeignKey反向引用创建相关字段。您应该在'Product'实例上尝试'my_product.variation_set'。有关详细信息,请参阅https://docs.djangoproject.com/en/1.8/topics/db/queries/#backwards-related-objects! –
产品有很多变体,变体的价格很多。你想展示什么? –