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
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 %}
- [Django]-Django settings based on IP or hostname
- [Django]-Subversion doesn't see my updates via python script
- [Django]-Django MultipleObjectsReturned