Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combing and sorting two querysets from different tables?

Tags:

django

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.

like image 384
user1328021 Avatar asked Jan 17 '23 00:01

user1328021


1 Answers

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)
like image 56
Chris Pratt Avatar answered Jan 30 '23 19:01

Chris Pratt