Skip to content

Commit

Permalink
refactor: better ordering of query result
Browse files Browse the repository at this point in the history
  • Loading branch information
ruthra-kumar committed Jan 16, 2024
1 parent 3349dde commit 519faba
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions erpnext/controllers/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
import frappe
from frappe import qb, scrub
from frappe.desk.reportview import get_filters_cond, get_match_cond
from frappe.query_builder import Criterion
from frappe.query_builder.functions import Concat, Sum
from frappe.query_builder import Criterion, CustomFunction
from frappe.query_builder.functions import Concat, Locate, Sum
from frappe.utils import nowdate, today, unique
from pypika import Order

import erpnext
from erpnext.stock.get_item_details import _get_item_tax_template
Expand Down Expand Up @@ -348,6 +349,8 @@ def get_project_name(doctype, txt, searchfield, start, page_len, filters):
proj = qb.DocType("Project")
qb_filter_and_conditions = []
qb_filter_or_conditions = []
ifelse = CustomFunction("IF", ["condition", "then", "else"])

if filters and filters.get("customer"):
qb_filter_and_conditions.append(proj.customer == filters.get("customer"))

Expand All @@ -368,8 +371,18 @@ def get_project_name(doctype, txt, searchfield, start, page_len, filters):
qb_filter_or_conditions.append(proj[x].like(f"%{txt}%"))

q = q.where(Criterion.all(qb_filter_and_conditions)).where(Criterion.any(qb_filter_or_conditions))

# ordering
if txt:
# project_name that contains the search string 'txt' will be given higher precedence
q = q.orderby(ifelse(Locate(txt, proj.project_name) > 0, Locate(txt, proj.project_name), 99999))
q = q.orderby(proj.idx, order=Order.desc).orderby(proj.name)

if page_len:
q = q.limit(page_len)

if start:
q = q.offset(10)
return q.run()


Expand Down

0 comments on commit 519faba

Please sign in to comment.