使用反向关系在 django 模型中获取 n 个项目
Get n items in django model using releverse relationship
可以使用反向关系获取 Django 模型中的最后 n 个项目。
{% for brand in brands %}
{% for product in brand.product_set.all %}
{% endfor %}
{% endfor %}
我试过这种方式,但是它打印了所有东西。但只想要最后 3 件商品
您可以使用 |slice
template tag [Django-doc] 来 切片 集合:
{% for brand in brands %}
{% for product in brand.product_set<strong>.reverse|slice:":3"</strong> %}
…
{% endfor %}
{% endfor %}
可以使用反向关系获取 Django 模型中的最后 n 个项目。
{% for brand in brands %}
{% for product in brand.product_set.all %}
{% endfor %}
{% endfor %}
我试过这种方式,但是它打印了所有东西。但只想要最后 3 件商品
您可以使用 |slice
template tag [Django-doc] 来 切片 集合:
{% for brand in brands %}
{% for product in brand.product_set<strong>.reverse|slice:":3"</strong> %}
…
{% endfor %}
{% endfor %}