[英]Django Queryset icontains() method not returning exact match
I am trying to filter a model, by passing the text query, and checking if any of the fields contains the value that matches exactly or partially to the given text query. 我试图通过传递文本查询来过滤模型,并检查是否有任何字段包含与给定文本查询完全匹配或部分匹配的值。
So let's say I have a model named Sample
, which contains char fields ["name", "state", "type"]
. 所以假设我有一个名为Sample
的模型,它包含char字段["name", "state", "type"]
。 Assuming one of the model object has a value of state
to set as "barely alive"
假设其中一个模型对象的state
值设置为"barely alive"
I looked at the methods described in the following django doc: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/search/ 我查看了以下django doc中描述的方法: https : //docs.djangoproject.com/en/2.1/ref/contrib/postgres/search/
I want to retrieve that object by using any of "barely"
, "arely"
or "barely alive"
as a text query. 我想通过使用任何"barely"
, "arely"
或"barely alive"
作为文本查询来检索该对象。
I initially tried something like Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search__icontains=query_text)
我最初尝试过类似Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search__icontains=query_text)
Above line will however, will not return a correct queryset if I pass a full text barely alive
as a query text and only work when partial text such as barely
or alive
is passed. 上述生产线将然而,将不如果我通过全文返回正确的查询集barely alive
的查询文本,只有当部分文字,如工作barely
或alive
传递。
So I then tried Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search=query_text).filter(search__icontains=query_text)
But then it returns an empty Queryset. 然后我尝试了Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search=query_text).filter(search__icontains=query_text)
但是它返回一个空的Queryset。
What am I missing here? 我在这里错过了什么?
PostgreSQL's full text search has quite a few intricacies with regard to partial matching, see eg here and here . PostgreSQL的全文搜索在部分匹配方面有很多复杂性,请参见此处和此处 。
However, if you can get by with an OR
query as you attempted, it's not difficult, you just need an appropriately constructed Q object instead of two chained filter
calls (because filter chaining uses AND
, not OR
). 但是,如果你可以在尝试时使用OR
查询,那就不难了,你只需要一个适当构造的Q对象而不是两个链式filter
调用(因为过滤器链接使用AND
,而不是OR
)。 So instead of 而不是
.filter(search=query_text).filter(search__icontains=query_text)
use 采用
.filter(Q(search=query_text) | Q(search__icontains=query_text))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.