我正在尝试通过 DetailView 显示该产品的产品和可用品牌(产品为 ForeignKey)。基于 Django 文档和 stackoverflow 上的类似答案,我尝试了下面的代码,但它不起作用。产品细节呈现,但品牌名称不是。我通过 django-admin 检查了数据库中产品的品牌。有人可以帮忙吗。
模型.py
class Product(models.Model):
name = models.CharField(max_length=256)
price = models.IntegerField()
class Brand(models.Model):
name = models.CharField(max_length=256)
product = models.ForeignKey(Product,on_delete=models.PROTECT,related_name='Brands')
视图.py
class ProductDetailView(DetailView):
model = Product
网址.py
path('detail/<int:pk>/',views.ProductDetailView.as_view(),name='product_detail'),
product_detail.html
<table class="table table-bordered table-hover table-secondary">
<tr>
<th class="bg-secondary th-customer-detail">Name</th>
<td>{{ product.name }}</td>
</tr>
<tr>
<th class="bg-secondary th-customer-detail">Price</th>
<td>{{ product.price }}</td>
</tr>
</table>
<br>
<ul>
{% for brand in product.brand_set.all %}
<li>{{ brand.name }}</li>
{% endfor %}
</ul>