backend/app/search/services/autocomplete_schema.py

50 lines
1.6 KiB
Python
Raw Normal View History

2022-10-22 13:11:30 +03:00
from typing import List, Dict
2022-10-22 03:09:14 +03:00
from search.models import Product, Category, Characteristic
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 = []
if not name_exclude:
schema.extend(
[
{
"coordinate": product["name"].lower().index(val.lower()),
"value": {
"type": "Name",
"value": product["name"],
},
}
for product in Product.objects.filter(name__unaccent__icontains=val)[
:20
].values("name")
2022-10-22 13:11:30 +03:00
]
)
if not category_exclude:
schema.extend(
[
{
"coordinate": cat["name"].lower().index(val.lower()),
"value": {"type": "Category", "value": cat["name"]},
}
for cat in Category.objects.filter(name__unaccent__icontains=val)[
:20
].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-22 12:29:51 +03:00
"coordinate": char["value"].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
]
)
return schema