Home Ask Login Register

Developers Planet

Your answer is one click away!

Eric Chen February 2016

Django Queryset for substr matching that starts from the beginning of a string

I have model Word, where every instance of the model stores a word or phrase in a field called text. e.g.,
"match sticks"

Now I want to construct a Django queryset such that given a query, I want to find all words that contains the query as a substring that starts from the beginning. For example, if my query is match:
"matches" - Yes, contains match as a substring that starts from the beginning
"match sticks" - Yes, similar to above
"notmatch" - No, because the substring doesn't start from the beginning

I can't use the "contain" field lookup directly because it doesn't match from the beginning. I could use "contain" then manually filter the results, but there could be a more efficient way. What's the most efficient way of doing this?


Shang Wang February 2016

Use startswith could only match the string from start:


django doc about startswith.

Post Status

Asked in February 2016
Viewed 2,769 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life