Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always True Q object

I want to create some part of Django ORM filter query dinamicly, now I can do:

if some:
   Obj.filter(
       some_f1=some_v1,
       f1=v1,
       f2=v2,
       f3=v3,
       f4=v4,
       ...
   )
else:
   Obj.filter(
       f1=v1,
       f2=v2,
       f3=v3,
       f4=v4,
       ...
   )

I want something without code duplicate like this:

Obj.filter(
    Q(some_f1=some_v1) if some else True,  # what to use instead of True?
    f1=v1,
    f2=v2,
    f3=v3,
    f4=v4,
    ...
)
like image 671
Ivan Borshchov Avatar asked Nov 04 '15 08:11

Ivan Borshchov


People also ask

What is Q object 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 Q object filters whether the question starts wiht 'what': from django. db.

How do I use ORM in Django?

To do so, open the Django shell to run the query. You might be wonder how Django ORM makes our queries executed or what the corresponding query of the code we are writing. It is quite simple to get the SQL query, we need to use the str() and pass the queryset object along with query.

What is PK in Django?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".

How do I join a query in Django?

Join QueriesJoin can be done with select_related method: Django defines this function as Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.


1 Answers

Here's a hacky way to get an always true Q object:

always_true = ~Q(pk=None)

This depends on the fact that the primary key cannot be null.

like image 67
Flimm Avatar answered Oct 09 '22 12:10

Flimm