I want to retrieve objects that contain a specific string in their CharField.
In normal Python without Django, I can do this to check:
if "something" in string:
pass
However, I don't know how to do so using .filter()
in Django:
posts = Post.objects.filter(field = "string") # how can I do something like 'in' here?
I don't just want to get objects that have exactly the value as "string".
Please teach me how to retrieve objects that contain a specific string in Django using .filter()
.
CodePudding user response:
You can use contains
. This will do case-sensitive containment test.
Post.objects.filter(field__contains='string')
This will generate the following SQL query.
SELECT ... WHERE field LIKE '%string%'
See field lookups for more information.
CodePudding user response:
posts = Post.objects.filter(field__icontains = "string")
Chack here details