Reputation: 197
I set up sorting related
to the object manager. I have views.py
def Objects(request):
Objects_1 = car_type_1.objects.filter(manager_id='1', is_published=True)
Objects_2 = car_type_2.objects.filter(manager_id='1', is_published=True)
Objects_3 = car_type_3.objects.filter(manager_id='1', is_published=True)
queryset_list = list(chain(Objects_1, Objects_2, Objects_3))
paginator = Paginator(queryset_list, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {'listings': paged_listings}
return render(request, 'template.html', context)
As a result, I get a page with objects. Responsible manager id 1
for all objects.
Everything is sorted correctly on the page. Showing manager id 1
objects. But, they are shown, one by one.
First all from the group car_type_1
, then the group car_type_2
and car_type_3
.
Question. How to make objects sorted by price
from all groups?
Thank!
Upvotes: 3
Views: 985
Reputation: 476557
You can sort the items in the list with sorted(..)
:
from operator import attrgetter
def objects(request):
objs1 = car_type_1.objects.filter(manager_id='1', is_published=True)
objs2 = car_type_2.objects.filter(manager_id='1', is_published=True)
objs3 = car_type_3.objects.filter(manager_id='1', is_published=True)
items = sorted(chain(objs1, objs2, objs3), key=attrgetter('price'))
paginator = Paginator(items, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {'listings': paged_listings}
return render(request, 'template.html', context)
But the above is not efficient if you need to sort huge amounts of data, since this will result in fetching all objects into memory and sorting these. Whereas a database usually is optimized to do the sorting on a limited result set.
It might be better to reconsider your design, and merge the three car_type_i
s into a single model.
Upvotes: 2