Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Sort objects in a chain

Tags:

python

django

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!

like image 468
I.Z. Avatar asked Sep 18 '25 05:09

I.Z.


1 Answers

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_is into a single model.

like image 168
Willem Van Onsem Avatar answered Sep 20 '25 18:09

Willem Van Onsem