I was developing with Django the other day and needed a search function. However, I always asked, "Well, how to narrow down the writing?", So I summarized it. I would appreciate it if you could point out any additional notes or mistakes.
Django's model has an attribute called object, which contains an instance of the Manager
class.
filter
is a function provided in this Manager
class, which is useful when you want to ** filter (narrow down) the data you want literally.
I have named it a strict search, but I will introduce a search that narrows down the search that exactly matches the content you want to filter.
This search finds ** case-sensitive exact matches **.
Example
user_name = "hoge" //Set the user name you want to find as a variable.
data = User.objects.filter(name=user_name)
Gets the name field in the User model that matches the user_name defined above. This will allow you to narrow down to just those that exactly match the name hoge.
Next, let's look at loose search. It's often the case when you say, "I don't know if hoge is the one that exactly matches the name, but if you're a person with a name like a messed up programmer called hogefugafoo."
In such a case, if you want to search not only for the exact match of "hoge" but also for ** including ** "hoge" **, this loose search is used.
Field name __contains = value
Field name __startswith = value
Field name __endswith = value
is.
Let's see how to use it concretely.
user_name = "fuga"
data = User.objects.filter(name__contains=user_name)
Now you can also get "hogefugafoo". The same applies to other searches.
user_name = "fuga"
data = User.objects.filter(name__startswith=user_name)
In this case, since it starts with "fuga", "hogefugafoo" does not match, but "fuga Taro" does.
user_name = "fuga"
data = User.objects.filter(name__endswith=user_name)
In this case, "hogefugafoo" does not match, but "Yamada johnfuga" does.
Now, at this point, you may want to do a looser search that doesn't distinguish between uppercase and lowercase letters. In such a case, just add ** ʻi` **.
Field name __iexact = value
Field name __icontains = value
-Search starting with ** **
Field name __istartswith = value
-Search ending in ** **
Field name __iendswith = value
Thank you for reading until the end. I will write about numerical search and AND search OR search with multiple conditions at a later date, so thank you for your cooperation.
Recommended Posts