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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With