Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queries: how to make contains OR not_contains queries

Tags:

python

django

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

like image 847
DataGreed Avatar asked Feb 25 '10 14:02

DataGreed


People also ask

What is __ str __ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is __ GTE in Django?

Definition and Usage. The gte lookup is used to get records that are larger than, or equal to, a specified value. For a greater than, but not or equal to, search, use the gt lookup.

What is F in Django QuerySet?

F() expressions. An F() object represents the value of a model field, transformed value of a model field, or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


1 Answers

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") )
like image 124
David Berger Avatar answered Nov 14 '22 22:11

David Berger