DataGreed
DataGreed

Reputation: 13899

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? ## ) )

Upvotes: 7

Views: 10807

Answers (1)

David Berger
David Berger

Reputation: 12803

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") )

Upvotes: 15

Related Questions