Search code examples
djangodjango-modelsormdjango-orm

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'

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].