【问题标题】:why prefetch_related not working in django?为什么 prefetch_related 在 Django 中不起作用?
【发布时间】:2020-06-06 18:50:10
【问题描述】:

我有这些模型

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 %}

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

【问题讨论】:

    标签: python django django-models django-views django-orm


    【解决方案1】:

    您指定了product_data.product_features,但product_dataProducts 的集合。应该是product.product_features(因为products是一个单一的Product对象,你最好把它命名为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 %}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2012-10-10
      • 2018-05-19
      • 2017-09-29
      • 2010-12-05
      • 1970-01-01
      相关资源
      最近更新 更多