I have two querysets that I would like to combine and sort.
Here are my queries:
latestbooks = Book.objects.all().order_by('-added')
latestvideos = Video.objects.all().order_by('-added')
I would like to combine these queries and sort them prior to passing them to my template so that I can create a list that shows the latest activity on the site -- whether it be a new book or new video in the order they were added in.
You can combine and sort them as lists but not as querysets. Functionality, it doesn't matter much, but bear in mind that no further filtering will be possible.
latestbooks = Book.objects.all().order_by('-added')
latestvideos = Video.objects.all().order_by('-added')
latest = list(latestbooks) + list(latestvideos)
latest_sorted = sorted(latest, key=lambda x: x.added, reverse=True)
UPDATE
If you're working with different attribute names, it's still possible, but it starts to get ugly, and this is probably not workable for more than just two variations:
sorted(latest, key=lambda x: x.added if hasattr(x, 'added') else x.desadded, 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