backend/app/search/services/autocomplete_schema.py

61 lines
2.1 KiB
Python
Raw Normal View History

2022-10-22 13:11:30 +03:00
from typing import List, Dict
2022-10-22 19:55:05 +03:00
from search.models import Product, Category, Characteristic, UnitCharacteristic
2022-10-22 03:09:14 +03:00
2022-10-22 05:07:25 +03:00
2022-10-22 13:11:30 +03:00
def autocomplete_schema(val: str, exclude: List[Dict]):
exclude = [dict(x) for x in exclude]
name_exclude = [x["value"] for x in exclude if x["type"] == "Name"]
category_exclude = [x["value"] for x in exclude if x["type"] == "Category"]
schema = []
2022-10-23 01:20:57 +03:00
if not category_exclude:
2022-10-22 13:11:30 +03:00
schema.extend(
[
{
2022-10-23 01:20:57 +03:00
"coordinate": cat["name"].replace("ё", "е").lower().index(val.lower()),
"value": {"type": "Category", "value": cat["name"]},
2022-10-22 13:11:30 +03:00
}
2022-10-23 01:20:57 +03:00
for cat in Category.objects.filter(name__unaccent__icontains=val)[
:10
].values("name")
2022-10-22 13:11:30 +03:00
]
)
2022-10-23 01:20:57 +03:00
if not name_exclude:
2022-10-22 13:11:30 +03:00
schema.extend(
[
{
2022-10-23 01:20:57 +03:00
"coordinate": product["name"].replace("ё", "е").lower().index(val.lower()),
"value": {
"type": "Name",
"value": product["name"],
},
2022-10-22 13:11:30 +03:00
}
2022-10-23 01:20:57 +03:00
for product in Product.objects.filter(name__unaccent__icontains=val)[
:30
].values("name")
2022-10-22 13:11:30 +03:00
]
2022-10-22 12:29:51 +03:00
)
2022-10-22 03:09:14 +03:00
schema.extend(
[
{
2022-10-23 01:20:57 +03:00
"coordinate": char["value"].replace("ё", "е").lower().index(val.lower()),
"value": {"type": char["name"], "value": char["value"]},
2022-10-22 05:07:25 +03:00
}
for char in Characteristic.objects.filter(value__unaccent__icontains=val)[
:20
].values("name", "value")
2022-10-22 03:09:14 +03:00
]
)
2022-10-22 19:55:05 +03:00
schema.extend(
[
{
2022-10-23 01:20:57 +03:00
"coordinate": char["name"].lower().replace("ё", "е").index(val.lower()),
2022-10-22 19:55:05 +03:00
"value": {
"type": char["name"] + "_numeric",
2022-10-23 01:20:57 +03:00
"value": char["name"]
2022-10-22 19:55:05 +03:00
}
2022-10-23 01:20:57 +03:00
} for char in UnitCharacteristic.objects.filter(name__unaccent__icontains=val)[:20].values("name", "value")
2022-10-22 19:55:05 +03:00
]
)
2022-10-22 03:09:14 +03:00
return schema