views:

61

answers:

1

Hello.

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

+5  A: 

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") )
David Berger
Wow, didn't know about ~ operator. Thank you very much!
DataGreed
Isn't it elegant? I love reusing low-level logic ideas in a higher level composition paradigm!
David Berger