首页 > 解决方案 > 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

标签: djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-templates

解决方案


您不应该在模板中加入。模板实现呈现逻辑,而不是业务逻辑。您可以使用以下方法枚举Option产品的相关 s:

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

因此,在视图中,您应该只传递products(not product,因为它是 s 的集合)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)
    )

推荐阅读