django - Django 简单模板标签问题
问题描述
我是一名正在学习如何玩 Django 的学生。您将使用 Vault 中的模板标签输出 p-tag。我要使用的模板标签是“当Option表中的option.product_code和product.product_code相同时,如果有两个options.option_code则打印出来”。我应该如何填写if语句?
我想补充
你好
通过参考上述。请给我一些建议。模型.py
class Product(models.Model):
product_code = models.AutoField(primary_key=True)
name = models.CharField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
class Meta:
ordering = ['product_code']
def __str__(self):
return self.name
class Option(models.Model):
option_code = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
def __str__(self):
return self.name
class Meta:
ordering = ['option_code']
视图.py
def index(request):
products = Product.objects.prefetch_related('option_set').annotate(noption=Count('option_set'))
return render(request, 'option/option_list.html', {'products':products})
模板
{% for product in products %}
{% for option in product.option_set.all %}
{% if product.noption >= 2 %}
<p> hello! </p>
{% endif %}
{% endfor %}{% endfor %}
错误 :
Cannot resolve keyword 'option_set' into field. Choices are: product_code, name, option
解决方案
您不应该在模板中加入。模板实现呈现逻辑,而不是业务逻辑。您可以使用以下方法枚举Option
产品的相关 s:
{% for product in products %}
<p>{{ product.name }}</p>
{% for option in product.option_set.all %}
option: {{ option.name }}
{% endfor %}
{% endfor %}
因此,在视图中,您应该只传递products
(not ,因为它是 s 的集合)product
Product
,并且通过使用.prefetch_related(…)
[Django-doc]您可以防止进行N+1查询:
def index(request):
products = Product.objects.prefetch_related('option_set')
return render(
request,
'option/option_list.html',
{'products': products)
)
推荐阅读
- java - 如何为 kafka 流使用多个使用相同主题的转换器?
- python - 通过在分类之前添加附加信息来自定义 CNN pytorch
- python - 循环链表的长度(python)
- php - 根据值添加或删除 PHP 字符串
- kubernetes - pod events 显示 persistentvolumeclaim "flink-pv-claim-11" 在 kubernetes 中被删除但绑定成功
- python - 如何从日期列中减去 5 年以在 python 数据框中创建新列?
- c# - C# Azure Devops API Git:如何使用 C# API 推送文件
- javascript - 面临在 React 中未清除间隔的问题
- maven - 未找到 Maven 依赖项但存在于 mvnrepository 中
- javascript - 错误:找不到模块“nexmo”和错误 TS2307:找不到模块 nexmo