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.,
"matches"
"match"
"match sticks"
"matching"
"notmatch"

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?

Answers


Shang Wang February 2016

Use startswith could only match the string from start:

Model.objects.filter(text__startswith="match")

django doc about startswith.

Post Status

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

Search




Leave an answer