为什么 prefetch_related 不能在 Django 中工作?

why prefetch_related not working in django?

我有这些模型

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_title = models.CharField(max_length=255, null = True)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name='product_features')
    product_feature_value = models.CharField(max_length=255, null = False)

所以我想为每个产品获取 product_features,我这样使用 prefetch_related:

product_data = Product.objects.filter(brand__brand_id = brand_data.brand_id).prefetch_related('product_features')

但在模板中,它现在显示相关的模型数据,这里是模板代码:

{% for products in product_data %}
      {{ products.product_name }}
      {% for a in product_data.product_features.all %}
         <li>{{ a.product_feature_value }}</li>
      {% endfor %}
{% endfor %}

请帮助我,我尝试了所有方法,但没有任何效果!

您指定了 product_data.product_features,但 product_data 集合 Product。它应该是 product.product_features(因为 products 是一个单独的 Product 对象,你最好将它命名为 product,而不是 products):

{% for <b>product</b> in product_data %}
      {{ <b>product</b>.product_name }}
      {% for a in <b>product</b>.product_features.all %}
         <li>{{ a.product_feature_value }}</li>
      {% endfor %}
{% endfor %}