[英]Simple Django queryset __icontains search that will find most specific elements first
I'm doing a queryset filter for "foo" in a CharField using __ictonains and I want to find the most specific search matches first. 我正在使用__ictonains在CharField中为“foo”做一个查询集过滤器,我想先找到最具体的搜索匹配。
Dataset in database for a certain field named "description": 数据库中某个名为“ description”的字段的数据集:
fooal;skdjfkasdgh;alskdjrf foobar foo-nstastical foobariffic foo-ntastic foo
When I search for: 当我搜索:
MyModel.objects.filter(description__icontains="foo")
The queryset returns the results in some order according to id number (or other factors?): 查询集根据ID号(或其他因素?)以某种顺序返回结果:
fooal;skdjfkasdgh;alskdjrf foobar foo-nstastical foobariffic foo-ntastic
If I only show the top 5 results I will leave out "foo" which is actually the best match that I want to show first. 如果我只显示前5个结果,我将省略“foo”,这实际上是我想要首先显示的最佳匹配。 How can I give higher weight to better matches in a simple way without implementing a "real heavy duty" search engine like Lucene? 如何在不实施像Lucene这样的“真正的重型”搜索引擎的情况下,以一种简单的方式就更好的比赛赋予更高的权重? I want an easier queryset filter hack. 我想要一个更简单的查询集过滤器黑客。
This is a crude search engine for a text dataset, the reason it is more important to show foo first when only showing the top N results is that if the person was looking for foobariffic, they could type in more letters. 这是一个用于文本数据集的粗略搜索引擎,当仅显示前N个结果时首先显示foo更为重要的原因是,如果该人正在寻找foobariffic,则他们可以输入更多字母。 But there is no way to get "foo" by typing more letters if it is displaced by longer entries. 但是,如果被更长的条目取代,则无法通过键入更多字母来获取“ foo”。
If it's a small field, you could potentially sort by field length and get good results. 如果这是一个很小的字段,则可以按字段长度排序并获得良好的结果。
Given a match, the shortest result is the hardest and most significant match. 给定匹配,最短的结果是最难和最重要的匹配。 Wouldn't work for full text of course... 当然不能用于全文...
I would be comfortable doing this for an autocomplete username or tag field. 对于自动填充用户名或标记字段,我会很自然地这样做。
foo
bofoo
foobar
barfood
Python sort Python排序
# python sort
x = [results]
x.sort(key=len)
Or in SQL 或在SQL中
MyModel.objects.extra(select={'myfield_length':'Length(myfield)'}).order_by('myfield_length')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.