Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Discombobulous Avatar asked Feb 08 '16 20:02

Discombobulous


People also ask

What is f() in Django?

F() can be used to create dynamic fields on your models by combining different fields with arithmetic: company = Company. objects. annotate( chairs_needed=F('num_employees') - F('num_chairs')) If the fields that you're combining are of different types you'll need to tell Django what kind of field will be returned.

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is the difference between contains and Icontains in Django?

Definition and Usage The contains lookup is used to get records that contains a specified value. The contains lookup is case sensitive. For a case insensitive search, use the icontains lookup.

What does .values do in Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.


1 Answers

Use startswith could only match the string from start:

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

django doc about startswith.

like image 167
Shang Wang Avatar answered Oct 04 '22 12:10

Shang Wang