1

我正在尝试通过 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>
4

1 回答 1

0

你可以这样做

class ProductDetailView(DetailView):
    model = Product
    context_object_name = 'product'

    def get_context_data(self,**kwargs):
        context = super(ProductDetailView,self).get_context_data(**kwargs)  #returns a dictionary of context
        primary_key = self.kwargs.get('pk')
        brands = Brand.objects.filter(product = primary_key)
        new_context_objects = {'brands':brands}
        context.update(new_context_objects)
        return context


<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 brands %}
      <li>{{brand.name}}</li>
  {% endfor %}

</ul>
于 2020-04-04T14:59:57.610 回答