Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

query in objects with django orm with a containing sentence

i have some city like this:

In [99]: City.objects.filter(title='Hamilton')
Out[99]: <QuerySet [<City: hamilton>]

i have some sentences like this:

sentence = ‘3101A 1280 Main Street West Hamilton ON L8S 4K1’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

how can i find cities that contains its title with this sentence?

Note: i have used this method but it is not True. because this query is useful for list not string in django:

In [100]: City.objects.filter(slug__in=sentence)
Out[100]: <QuerySet []>

>Solution :

You can use the Contains lookup for case-insensitive substring search:

from django.db.models import F, Value
from django.db.models.lookups import Contains

City.objects.filter(Contains(Value(sentence), F('title')))

While using the __icontains lookup [Django-doc] produces results for text, this often is still a poor way to search, since it will only fetch items with the exact string. Usually one uses solutions like Elastic or Solr, or one can uses PostgreSQL‘s __search lookup [Django-doc].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading