tlunter
tlunter

Reputation: 724

Reordering Modified QuerySet

My database is set up with a list of cases with an ID from our ticketing system, a location, an assigned person and a short description taken from the ticket:

Now to help better sort things, depending on certain status values, we change the QuerySet after querying it.

current_active = Case.objects.filter(queue_num=0,status__lt=6)
for item in current_active:
    if(item.location == 'NPH'):
        item.assigned_tech = 'NPH'
    elif(item.location == 'Bins'):
        item.assigned_tech = 'Bins'
    elif(item.status > '2' and item.status < '6'):
        item.assigned_tech = 'Pending'

I was wondering if there was any way to sort this new modified QuerySet. We know it prints correctly, it just comes down to the sorting that gets messed up.

UPDATE 2

current_active = Case.objects.filter(queue_num=0,status__lt=6)
current_active_list = []
for item in current_active:
    number = item.id
    item.id = '%07d' % number
    phone = item.myneuname.phonenumber
    if(len(phone) > 7):
        formattedPhone = phone[:-10]+' ('+phone[-10:-7]+') '+phone[-7:-4]+'-'+phone[-4:]
        item.myneuname.phonenumber = formattedPhone
    if(item.location == 'NPH'):
        item.assigned_tech = 'NPH'
    elif(item.location == 'Bins'):
        item.assigned_tech = 'Bins'
    elif(item.status > '2' and item.status < '6'):
        item.assigned_tech = 'Pending'
    current_active_list.append(item)
current_active_list.sort(key=lambda x: x.assigned_tech)

While this is not idea and Django-style, this does work. If you have the same issue and find a more reasonable way to fix this problem, please don't hesitate to reply. Making a Python list seemed the only way possible without saving data.

Upvotes: 0

Views: 154

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599956

Since you're evaluating the queryset and then modifying some of the elements without saving, you need to avoid anything that goes back to the database and re-evaluates it. In your case, there's nothing wrong with simply ordering the list in Python - for example:

current_active.sort(key=lambda x: x.assigned_tech)

to sort by the assigned_tech field.

Upvotes: 2

Abid A
Abid A

Reputation: 7858

Not sure how you would sort that same QuerySet based on your new property, but if you were to append each item into a new list (after assigning assigned_tech to each item), you could do something like this:

import operator
new_list.sort(key=operator.attrgetter('assigned_tech'))

And to reverse the sort order:

import operator
new_list.sort(key=operator.attrgetter('assigned_tech'), reverse=True)

But if you find a way to do it without creating a new list, that would obviously be better and I would love to see it.

Upvotes: 0

diegueus9
diegueus9

Reputation: 31582

Maybe you're talking about order_by method of django's ORM

Upvotes: 1

Related Questions