Sandy Sandy - 3 months ago 24
Python Question

Django+python: Use Order by to Django RawQuery objects?

I have almost 100 million product names present in DB.I am displaying 100 products in UI each time & after scrolling showing next 100 & so on. For this I have used Django RawQuery as my database(mysql) doesn't support distinct functionality.

Here 'fetch' is callback function used in otherfile:

def fetch(query_string, *query_args):

conn = connections['databaseName']
with conn.cursor() as cursor:
cursor.execute(query_string, query_args)
record = dictfetchall(cursor)
return record


Here is the main call in views.py
So sample raw query code snippet:

record= fetch("select productname from abc")


Here if I am going to apply sorting criteria to the records

record= fetch("select productname from abc orderby name ASC")


Same doing for descending as well. As a result it takes so much time to display the sorted products.

What I want is like I will query 1 time & will store in a python object then will start applying ascending or descending.

So that for the first time when it loads, it will take some time but then applying sorting criteria it won't go to database to apply sorting for each time sort is hitted.

Overally want to say increase performance in case of sorting the records.

Answer

Below is my try & I got the desired answer.

I fetch the data from database & is stored in the form of array of dictionary in a list.

Assuming the data stored format in a list:

l = [{'productName'='soap',id=1},{'productName'='Laptop',id=2}]

Below code snippet is the solution to sort dependening upon key:

from operator import itemgetter

for Ascending

res= sorted(l, key=itemgetter('name'))

For Descending

res= sorted(l, key=itemgetter('name'),reverse=True)
Comments