5

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?

1 Answer 1

17

Use startswith could only match the string from start:

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

django doc about startswith.

2

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.