feat: table_field.fieldname field syntax for db_query

This commit is contained in:
Faris Ansari 2022-05-27 16:04:22 +05:30
parent 6e53c3d339
commit 96b30e714c
3 changed files with 42 additions and 2 deletions

View file

@ -171,7 +171,7 @@ def raise_invalid_field(fieldname):
def is_standard(fieldname):
if "." in fieldname:
parenttype, fieldname = get_parenttype_and_fieldname(fieldname, None)
fieldname = fieldname.split(".")[1].strip("`")
return (
fieldname in default_fields or fieldname in optional_fields or fieldname in child_table_fields
)
@ -235,7 +235,16 @@ def parse_json(data):
def get_parenttype_and_fieldname(field, data):
if "." in field:
parenttype, fieldname = field.split(".")[0][4:-1], field.split(".")[1].strip("`")
parts = field.split(".")
parenttype = parts[0]
fieldname = parts[1]
if parenttype.startswith("`tab"):
# `tabChild DocType`.`fieldname`
parenttype = parenttype[4:-1]
fieldname = fieldname.strip("`")
else:
# tablefield.fieldname
parenttype = frappe.get_meta(data.doctype).get_field(parenttype).options
else:
parenttype = data.doctype
fieldname = field.strip("`")

View file

@ -287,6 +287,21 @@ class DatabaseQuery(object):
# remove empty strings / nulls in fields
self.fields = [f for f in self.fields if f]
# convert child_table.fieldname to `tabChild DocType`.`fieldname`
for field in self.fields:
if "." in field and "tab" not in field:
original_field = field
alias = None
if " as " in field:
field, alias = field.split(" as ")
tablefield, fieldname = field.split(".")
child_doctype = frappe.get_meta(self.doctype).get_field(tablefield).options
field = field.replace(tablefield, f"`tab{child_doctype}`")
field = field.replace(fieldname, f"`{fieldname}`")
if alias:
field = f"{field} as {alias}"
self.fields[self.fields.index(original_field)] = field
for filter_name in ["filters", "or_filters"]:
filters = getattr(self, filter_name)
if isinstance(filters, str):

View file

@ -35,6 +35,22 @@ class TestReportview(unittest.TestCase):
clear_custom_fields("DocType")
def test_child_table_field_syntax(self):
note = frappe.get_doc(
doctype="Note",
title=f"Test {frappe.utils.random_string(8)}",
content="test",
seen_by=[{"user": "Administrator"}],
).insert()
result = frappe.db.get_all(
"Note",
filters={"name": note.name},
fields=["name", "seen_by.user as seen_by"],
limit=1,
)
self.assertEqual(result[0].seen_by, "Administrator")
note.delete()
def test_build_match_conditions(self):
clear_user_permissions_for_doctype("Blog Post", "test2@example.com")