Django 简单模板标签问题

Django Simple Template Tag Questions

我是一名正在学习如何玩 Django 的学生。您将要使用保险库中的模板标签输出 p 标签。我要使用的模板标签是“当option.product_code和product.product_code在Optiontable中相同时,如果有两个options.option_code则打印出来”。我应该如何填写if语句?

参考以上内容补充

你好

。请给我一些建议。

Models.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']

views.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

你不应该在模板中加入。模板实现呈现逻辑,而不是业务逻辑。您可以枚举产品的相关 Options:

{% for product in products %}
    <p>{{ product.name }}</p>
    {% for option in <strong>product.option_set.all</strong> %}
        option: {{ option.name }}
    {% endfor %}
{% endfor %}

在视图中,您因此应该只传递 products(而不是 product,因为它是一个 集合Products),并且通过使用 .prefetch_related(…) [Django-doc] 可以防止进行 N+1 查询:

def index(request):
    products = Product.objects<strong>.prefetch_related('option_set')</strong>
    return render(
        request,
        'option/option_list.html',
        {<strong>'products'</strong>: products)
    )