首页 > 解决方案 > 为什么 prefetch_related 在 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 %}

请帮助我,我尝试了一切,但没有任何效果!

标签: pythondjangodjango-modelsdjango-viewsdjango-orm

解决方案


您指定product_data.product_features, butproduct_data是s的集合Product它应该是product.product_features(因为products是单个Product对象,你最好命名为 this product,而不是products):

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

推荐阅读