Home > Enterprise >  Get n items in django model using releverse relationship
Get n items in django model using releverse relationship

Time:11-11

Is possible to get the last n items in the Django model, using the reverse relationship.

 {% for brand in brands %}

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

     {% endfor %}

{% endfor %}

I am tried in this way, But it prints all things. But want only last 3 items

CodePudding user response:

You can make use of the |slice template tag [Django-doc] to slice the collection with:

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