Sort a list from different classes by one field – Django

Question:

I connect multiple queryset from different objects into one list:

query_1 = Room.objects.all()
query_2 = Apartment.objects.all()
query_3 = Plot.objects.all()

all_user_objects = list(chain(query_1, query_2, query_3))

How can I add a sort by created_at date from the newest?

I try this:

all_user_objects.order_by('-created_at')

and this:

from operator import attrgetter
all_user_objects = list(chain(query_1, query_2, query_3), key=attrgetter('-created_at'))
Asked By: Maddie Graham

||

Answers:

You can use sorted() for this:

from operator import attrgetter

all_user_objects = list(sorted(chain(query_1, query_2, query_3), key=attrgetter('created_at'), reverse=True))
Answered By: Linh Nguyen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.