Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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

def query_to_full_post_data_serializer(request, post_query_set: QuerySet):
    query_set_annotated = post_query_set.annotate(
        creator_username=F('creator__username'),
        creator_avatar_url=F('creator__avatar')
    )
    return FullPostDataSerializer(query_set_annotated, many=True)

@api_view(['GET'])
def get_newer_posts(request, post_uuid, count):
    query = generate_followee_or_join_goal_follow_query(request)
    query = query & Q(uuid__gt=post_uuid)
    serializer = query_to_full_post_data_serializer(request=request, post_query_set=Post.objects.filter(query).order_by('uuid')[:count])
    return Response(serializer.data, status=status.HTTP_200_OK)

serializer.py

class FullPostDataSerializer(serializers.ModelSerializer):
    creator_username = serializers.SlugField()
    creator_avatar_url = serializers.SlugField()

    class Meta:
        model = Post
        fields = (
            'body', 'created', 'creator_username', 'uuid', 'creator', 'creator_avatar_url')

Tried Solutions

-

serializer.data.reverse()

doesn't reverse the list for some reason.

  • tried to order_by on the slice, but this isn't allowed by Django
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

items = serializer.data
items.reverse()
return Response(items, status=status.HTTP_200_OK)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!