[Answer]-Django Weird behavior while extracting last element from a list at views.py

0👍

Oki, guys, the problem came from apache server which needed to be reloaded (there is no need to do so with PHP, that’s why I haven’t thought of it).

I also have replaced
messages = get_list_or_404(Message.objects.order_by(‘publication_date’))
by
last = get_list_or_404(Message).latest(‘publication_date’)
Which is more concise.

Thanks for your help and answers!

1👍

I’d do it this way to ensure you’re only pulling back one object instead of all the messages each time:

messages = Message.objects.order_by('-publication_date')[:1]
if not messages:
    raise Http404
last = message[0]

Alternatively you could do:

try:
    last = Message.objects.order_by('-publication_date')[0]
except IndexError:
    raise Http404
👤Tom

Leave a comment