Home > Enterprise >  Limiting the queryset displayed after the foreign key in the template - Django
Limiting the queryset displayed after the foreign key in the template - Django

Time:11-20

I know how to return all objects by a foreign key in a Django template. But how to limit their number to the last 3? Is it possible?

Example

Models.html

class Person(models.Model):
    ...

class Tag(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    name = models.CharField(max_length=10)

Template.html

{% for tag in person.tag_set.all %}
    ...
{% endfor %}

What is expected (only the last 3 objects)?

{% for tag in person.tag_set.all[:3] %}
    ...
{% endfor %}

CodePudding user response:

Use the slice template filter to slice a queryset/list, this gets the first 3 items

{% for tag in person.tag_set.all|slice:":3" %}

Negative indexing of querysets is not supported, getting the last three would be complex in a template

CodePudding user response:

Not sure if it possible to use in template, but you can prepare your queryset using reverse(). https://docs.djangoproject.com/en/dev/ref/models/querysets/#reverse

  • Related