1

I'd like to display a fixed-length subset of a set of related objects in a Django template. For example, imagine that I have a Car, which has related object Owner. I would like to display the three most recent owners, but also always display three entries even if there are fewer. So

Ford Fiesta AA11 1AA
    1. John Smith
    2. Jane Smith
    3. Jenny Smith

Aston Martin DB9
    1. Richard Rich
    2.
    3.

even if the Fiesta has had 10 owners (and the DB9 has had only one).

The naive way to do this would be

<h1>{{car.name}}</h1>
<ol>
  {% for owner in car.owner_set|slice:":3" %}
  <li>{{owner.name}}</li>
  {% endfor %}
</ol>

but this will only display one list item if there has only been one owner.

I could also add lines like

{% if car.owner_set|length < 2 %}<li></li>{% endif %}
{% if car.owner_set|length < 3 %}<li></li>{% endif %}

but that's terrible. Is there a nicer way to do this?

3 Answers 3

3

The easiest way seems to me to be to define a new filter.

Create a templatetags package in the relevant app and add a file called liststuff.py (or whatever name you wish) with the following code:

from django import template

register = template.Library()


@register.filter
def exactlength(listlike_thing, desired_length):
    list_thing = list(listlike_thing)
    if len(list_thing) < desired_length:
        # pad the list with as many empty strings as needed
        list_thing += ([''] * (desired_length - len(list_thing)))
    return list_thing[:desired_length]

Then, at the top of your template, load that file (if you called your file something else, change this line accordingly):

{% load liststuff %}

and in your loop initialisation, pass your values through the filter:

{% for owner in car.owner_set|exactlength:3 %}
2

You could create a custom filter or similar, but for just the one instance, I would add a method to the Car model that returned what you're after, something like:

def three_latest_owners(self):
    num = 3
    latest = list(self.owner_set.all()[:num])
    latest += [None] * num
    return latest[:num]

Then in the template, {% for owner in car.three_latest_owners %}

2

Obviously, not the most elegant solution nor the most re-usable, but the real naive solution would surely be:

<h1>{{car.name}}</h1>
<ol>
  <li>{{car.owner_set.0.name}}</li>
  <li>{{car.owner_set.1.name}}</li>
  <li>{{car.owner_set.2.name}}</li>
</ol>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.