Django queries: how to make contains OR not_contains queries
I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely?
Seems something like:
Record.objects.filter( Q(parameter__icontains="wd2") | 开发者_运维问答Q( ## what should be here? ## ) )
From the django q object documentation:
You can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query:
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
So I would recommend
Record.objects.filter( Q(parameter__icontains="wd2") | ~Q(parameter__icontains="wd") )
精彩评论