如何在Django模板中显示N个Backward关系?

How to display N number of Backward relationship in Django templates?

{% for category in categories %}
    {% for product in categories.product_set.all %}
        <h1> {{ product.name }} </h1>
    {% endfor %}
{% endfor %}

我想显示 10 个产品而不是模板中的所有产品

您可以在模板中使用 slice 过滤器:

{% for category in categories %}
    {% for product in categories.product_set.all|slice:":10" %}
        <h1> {{ product.name }} </h1>
    {% endfor %}
{% endfor %}