From 3d00c93822156f6eb142d02f8226f5e851b9e937 Mon Sep 17 00:00:00 2001 From: Mihir Kandoi Date: Tue, 23 Jun 2026 19:35:35 +0530 Subject: [PATCH] fix(stock): keep item-search ordering for Quality Inspection on Postgres (#56372) The Quality Inspection item link search builds a distinct, paginated get_query with order_by="items.item_code". frappe's db_query silently drops the ORDER BY for a distinct query on Postgres, so with offset/limit the results come back in a different order AND a different page slice than MariaDB. Append the ordering to the built query instead of passing order_by: item_code is already in the DISTINCT select list, so ORDER BY on it is valid under DISTINCT on Postgres, and it now applies before LIMIT on both engines. MariaDB output is unchanged (it was already ordered by item_code). The items child field is guarded for None so a doctype without it degrades gracefully rather than raising AttributeError. --- .../doctype/quality_inspection/quality_inspection.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/erpnext/stock/doctype/quality_inspection/quality_inspection.py b/erpnext/stock/doctype/quality_inspection/quality_inspection.py index 7a99553aea0..ff536f01d55 100644 --- a/erpnext/stock/doctype/quality_inspection/quality_inspection.py +++ b/erpnext/stock/doctype/quality_inspection/quality_inspection.py @@ -413,16 +413,22 @@ def item_query(doctype: Any, txt: str | None, searchfield: Any, start: int, page ] ) - return frappe.get_query( + query = frappe.get_query( reference_doctype, fields=["items.item_code, items.item_name"], filters=my_filters, offset=start, limit=page_len, - order_by="items.item_code", ignore_permissions=False, distinct=True, - ).run() + ) + # frappe's db_query drops ORDER BY for a distinct query on Postgres, which (with offset/limit) + # changes both the order and the page contents vs MariaDB. Appending the order to the built + # query instead keeps it -- item_code is in the DISTINCT select, so it is valid on Postgres. + items_field = frappe.get_meta(reference_doctype).get_field("items") + if items_field: + query = query.orderby(frappe.qb.DocType(items_field.options).item_code) + return query.run() @frappe.whitelist()