[Django]-"Last" tag not working

4πŸ‘

βœ…

The last tag works by slicing a list to get the last item, using the negative index format: collection[-1]. But as the error message points out, negative indexing is not supported on querysets.

Probably the easiest way of solving this is to create a new method on your Promotion model to return the last appointment:

class Promotion(models.Model):
    ... fields, etc ...

    def get_last_appointment(self):
        try:
            return self.appointment_set.all().order_by('-date')[0]
        except IndexError:
            pass

and call this from the template:

{{ promotion.get_last_appointment.date|date }}

5πŸ‘

Converting the queryset into a list before giving it to the template also gets you where you want to go:

return render_to_response(template, { 
     appointments: list(Appointments.objects.all()) 
})

Since I’m using the whole list I do something like this (which might be open to improvement):

{% for ap in appointments %}
  {% ifequal ap appointments|last %}
    ap.date
  {% endifequal %}
{% endfor %}

The object attributes still work. eg: ap.user.full_name

πŸ‘€John Mee

4πŸ‘

The cause of your problem is what @Daniel pointed out: Querysets do not support negative indexing. His solution is worth exploring.

Another way of addressing this is to add a custom filter that will work with lists and querysets. Something like:

@register.filter
def custom_last(value):
    last = None

    try:
        last = value[-1]
    except AssertionError:
        try:
            last = value.reverse()[0]
        except IndexError:
            pass

    return last

And in the template:

{% with appointments|custom_last as last_ap %}

Leave a comment