【问题标题】:Get n items in django model using releverse relationship使用反向关系在 django 模型中获取 n 个项目
【发布时间】:2021-12-23 23:01:02
【问题描述】:

有可能得到Django模型中的最后n个项目,使用反向关系。

 {% for brand in brands %}

     {% for product in brand.product_set.all %}

     {% endfor %}

{% endfor %}

我尝试过这种方式,但它会打印所有内容。但只想要最后 3 项

【问题讨论】:

    标签: python python-3.x django django-models django-templates


    【解决方案1】:

    您可以使用|slice template tag [Django-doc] 对集合进行切片

    {% for brand in brands %}
        {% for product in brand.product_set.reverse|slice:":3" %}
            …
        {% endfor %}
    {% endfor %}

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 2022-06-22
      • 2021-11-16
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多