How to achieve multiple sorting levels in Django ORM Queries

Viewed 43

On the below Posts model , I need to sort the posts by both date and likes. the results should be last 24 hr posts ,sorted by likes , then the next day posts sorted by likes , it goes on..

class Posts(models.Model):
    comment_text= models.CharField(max_length=1000)
    date        = models.DateTimeField(default=timezone.now())
    likes       = models.IntegerField(default=0)

views.py

latest=Posts.objects.filter().order_by(-date,-likes)

the above query is not giving the desired results , let us say if there are two posts created at 07/06/2021 at 1 pm which has 3 likes and another one at 1:30 pm which as 1 like.

Then the post created at 1:30 pm with 1 like comes on top instead of the post at 1 pm with 3 likes

1 Answers

You can use TruncDate [Django docs] to annotate the truncated date to the queryset and order using that:

from django.db.models.functions import TruncDate


latest = Posts.objects.annotate(truncated_date=TruncDate('date')).order_by('-truncated_date', '-likes')

Note: A DateTimeField being named date is a bit weird yes? Consider renaming it.

Related