Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Extracting a `Q` object from a `QuerySet`

I have a Django QuerySet, and I want to get a Q object out of it. (i.e. that holds the exact same query as that queryset.)

Is that possible? And if so, how?

like image 443
Ram Rachum Avatar asked Mar 14 '12 14:03

Ram Rachum


People also ask

How do I cut a QuerySet in Django?

Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python's array-slicing syntax. Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet , but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list.

How do you use Q objects in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this statement returns if the question starts with 'who' or with 'what'.

Is Django QuerySet lazy?

QuerySet s are lazy Though this looks like three database hits, in fact it hits the database only once, at the last line ( print(q) ). In general, the results of a QuerySet aren't fetched from the database until you “ask” for them.


1 Answers

No, but you could create the Q object first, and use that; alternatively, create your query as a dict, and pass that to your filter method and the Q object.

like image 171
Marcin Avatar answered Sep 26 '22 03:09

Marcin