简体   繁体   中英

why prefetch_related not working in django?

I have these models

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)

So I want to fetch product_features for each product and i used prefetch_related like this:

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

but in template it's now showing related model data here's template code:

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

Please help me I tried everything but nothing works!

You specify product_data.product_features , but product_data is a collection of Product s. It should be product.product_features (since products is a single Product object, you better name this product , not products ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM