2👍
This is not exactly a QuerySet problem.
This needs a separate algo that decides the ordering of the result set that you create. I would write a new algo that decides the ordering – possibly a whole array of algos because your results would depend on the category
of the query itself.
For now I can think of adding weight to the every result in the result set, deciding how close it is to the query done, based on some parameters.
In your case, your parameters would be as follows:
- How many words matched?
- The words that appear first should get the highest priority
- Any query that matches fully should have the highest priority as well
- The words on the far end of the query should have lowest priority
Anyways, that is an idea to begin with, I am sure you will have it much more complex perhaps.
So here’s the code for create the ordering:
query = 'green shoe'
query_with_weights = [(x, len(query.split()) - query.split().index(x)) for x in query.split()]
results = ['black pants', 'green pants', 'green shoe']
results_split = [res.split() for res in results]
get_weight = lambda x: ([weight for y, weight in query_with_weights if y==x] or [0])[0]
sorted_results = sorted([ (l, sum([( get_weight(m)) for m in l])) for l in results_split], key = lambda lst: lst[1], reverse=True)
print('sorted_results={}'.format(sorted_results))
Once you try this, you will get the following results:
sorted_results=[([‘green’, ‘shoe’], 3), ([‘green’, ‘pants’], 2),
([‘black’, ‘pants’], 0)]
I hope this explains the point. However, this algo will only work for simple text. You might have to change your algo based on electrical items, for example, if your website depends on it. Sometimes you may have to look into properties of the object itself. This should be a good starter.