Django queries: how to do contains OR not_contains queries

I need to make a request that will receive records containing the substring "wd2" or not containing the string "wd" at all. Is there any way to make it beautiful?

It seems something like:

Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )

+6
python django
source share
1 answer

From the django q documentation:

You can make statements of arbitrary complexity by combining Q objects with and and | operators and use brackets. In addition, Q objects can be nullified using the ~ operator, which allows you to combine a search that combines both a regular query and a negative (NOT) query:

 Q(question__startswith='Who') | ~Q(pub_date__year=2005) 

Therefore I would recommend

 Record.objects.filter( Q(parameter__icontains="wd2") | ~Q(parameter__icontains="wd") ) 
+13
source share

All Articles