Home > Enterprise >  Sort a list from different classes by one field - Django
Sort a list from different classes by one field - Django

Time:08-06

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'))

CodePudding user response:

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))
  • Related