[英]Display values from foreign key in Django Admin
I am trying to show values from a foreign key in my model value (in admin). 我试图在我的模型值(在admin中)中显示来自外键的值。
I am using "except" tho I am I should use explicit. 我使用的是“除外”,我应该使用显式的。 How do I use this?
我该如何使用? And how to I get the below working correctly?
以及如何使以下内容正常工作? It just shows (none) but there is a value there.
它只是显示(无),但那里有一个值。
Thanks 谢谢
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
Let's try to simplify your code. 让我们尝试简化您的代码。
Instead: 代替:
price = Price.objects.filter(variation=Variation.objects.filter(product=obj)[0])
You can write: 你可以写:
price = Price.objects.filter(variation__product=obj)
Filter return QuerySet, but You want to have one price: 过滤器返回QuerySet,但是您要一个价格:
price = Price.objects.filter(variation__product=obj)[0]
When no price found, You want to write None
, else price.price: 如果找不到价格,则要写
None
,否则要写price.price:
try:
price = Price.objects.filter(variation__product=obj)[0].price
except Price.DoesNotExist:
price = 'None'
return format_html('<center><b>"{0}"</b></center>', price)
And finally "explicit" version: 最后是“显式”版本:
prices = Price.objects.filter(variation__product=obj)
price = prices[0].price if prices.exists() else 'None'
return format_html('<center><b>"{0}"</b></center>', price)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.