1

I have a model in Django like this -

class City:
    name = models.CharField(max_length=255)

Now the below query can filter if the parameter string is a substring of the name field in the City model --

results = City.objects.filter(name_icontains=<some_string>).all()

So suppose one of the rows in the database for city table has name = "new york city", so if the give the querystring as "new york", the above filter query will match with it since "new york" is contained in the "new york city".

Now after reading the answer to this question --

Django, how to use filter to check if string field is contained in parameter

I could solve this by breaking the querystring into words and then applying filter query for each of them. However, how to solve this if my querystring is not two separate words but a long word. Here is an example -

Suppose one row for city table contains name as "newyork" and my query string is "newyorkcity", now I can not break the "newyorkcity" querystring into separate words and apply separate filtering. So how can I solve this problem so that when I search for rows matching name as "newyorkcity", it should return the rows which contain name as "newyork"?

I hope I was clear in my explanation.

Thanks

1 Answers1

1

Can you try this query?

City.objects.annotate(
    string=Value('newyorkcity', output_field=CharField())
).filter(string__icontains=F('name'))
funnydman
  • 9,083
  • 4
  • 40
  • 55
  • Having `output_field=CharField()` in your mentioned query gives this error `CharField object has no attribute 'get_lookup'` but the query works fine after removing the output_field parameter. – Ashutosh Feb 24 '22 at 06:17