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?
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.
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.
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.
Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.
Use startswith
could only match the string from start:
Model.objects.filter(text__startswith="match")
django doc about startswith.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With