Python 我可以引用Django'中外键的单个值吗;什么样的模板?
我有一个模型:Python 我可以引用Django'中外键的单个值吗;什么样的模板?,python,django,django-views,django-templates,Python,Django,Django Views,Django Templates,我有一个模型: `class product(models.Model): product = models.CharField(primary_key=True, unique=True, max_length=7, editable=False) desc = models.CharField(max_length=50) class pricelist(models.Model): product = models.ForeignKey(product, on_
`class product(models.Model):
product = models.CharField(primary_key=True, unique=True, max_length=7, editable=False)
desc = models.CharField(max_length=50)
class pricelist(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE)
price_group = models.ForeignKey(pricegroup, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=8, decimal_places=2, null=True)`
基本上,我有4个不同的价格组(一个产品最多可能有4个不同的价格-每个价格组一个),我想在我的产品模板(DetailView)上显示指定(过滤)价格组的产品价格
假设我有以下价格组:“PG1”、“PG2”、“PG3”、“PG4”
我能够循环浏览它们的列表:
{% for pricelist in product.pricelist.all %}
{{ pricelist.price }}
{% endfor %}
但我无法仅显示两个指定价格组的价格。
我需要以以下方式在我的网页上显示价格:
PG1 = 124
PG3 = 367
有时只有两个或三个组的价格可用您需要在视图中预渲染数据,然后将其作为上下文传递给模板。在模板中使用自定义过滤器有一个很好的选择,但即使是这些过滤器也需要额外的信息才能工作 好的,下面是@tstoev的回答,我和decorator一起工作时得到的结果:
@property
def PricePG1(self):
return pricelist.objects.filter(price_group__exact='PG1', product_id=self)[0].price
谢谢这可能是数据库体系结构问题。如果只有固定数量的四个price_组,为什么要使用ForeignKey字段?为什么不为四个组使用带有
choice
元素的CharField呢?组与外部系统同步,将来它们的数量可能会增加。谢谢你的评论