简体   繁体   中英

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"] . Assuming one of the model object has a value of state to set as "barely alive"

I looked at the methods described in the following 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.

I initially tried something like 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.

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.

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 .

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 ). So instead of

.filter(search=query_text).filter(search__icontains=query_text)

use

.filter(Q(search=query_text) | Q(search__icontains=query_text))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM