python - 为什么 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 %}
请帮助我,我尝试了一切,但没有任何效果!
解决方案
您指定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 %}
推荐阅读
- database - JPG 图像扩展名未插入到 wp 的自定义表中
- java - Microsoft SQL Server:“登录失败。登录来自不受信任的域,不能用于 Windows 身份验证。”
- java - 如何从控制台启动我的应用程序作为服务器?
- node.js - Mongoosastic 不保存索引
- r - 从 R 闪亮的打开对话框中停止 dropdownButton(闪亮的小部件)
- unity3d - 无法运行函数。重载需要 0 个参数
- angular - 获取用户时区角度 5 + ngx-moment 的时间
- jquery - 为什么选择类返回未定义的值?
- clojure - 在clojure中平衡两个向量的功能方法
- java - 继承链,子类不是覆盖方法