Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order 2 different querysets by date

This is a simple question, I could achieve this with a for loop and lots of comparisons, but I am wondering if there is a better way.

I have two querysets:

  comments = Comment.objects.all()
  actions = Action.objects.all()

So, I need a list with both comments and actions ordered by date. The Comment model and the Action model have a date (date=models.DateTimeField(auto_now_add=True)) field.

In other words:

wall = [] # Alternate Comments and Actions ordered by date
like image 803
Alejandro Veintimilla Avatar asked Jan 22 '26 12:01

Alejandro Veintimilla


1 Answers

You can have list of combined comments and actions

comments = Comment.objects.all()
actions = Action.objects.all()
from itertools import chain
wall = list(chain(comments, actions))

You can sort then the python list of objects by attribute, which is date in your case

wall.sort(key=lambda x: x.date)

You can also pass reverse True/False in lambda function, for descending and ascending order

wall.sort(key=lambda X:x.date, reverse=True)
like image 130
Pradnya Mhatre Avatar answered Jan 25 '26 01:01

Pradnya Mhatre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!