Skip to content
Advertisement

Django – Ensure ordering of response data is newer first

So I have some code below that returns posts that are newer than a post with post_uuid given. This is ensured because I force an ordered uuid scheme where each Post is given a uuid in order of creation, this is done with ulid. I want to enforce that that the returned serializer.data is ordered by Post creation data, with the newest best first or index=0 and oldest being last. How do I ensure this?

view.py

JavaScript

serializer.py

JavaScript

Tried Solutions

JavaScript

doesn’t reverse the list for some reason.

  • tried to order_by on the slice, but this isn’t allowed by Django

Advertisement

Answer

The serializer.data is a property, so calling .reverse() on it, will not work, since you reverse the result of the property, but the next call to serializer.data will again trigger to property that will construct a new list.

You thus fetch the data, and then reverse that data and pass it as result:

JavaScript
Advertisement