Answer the question
In order to leave comments, you need to log in
How to query a Django model based on the contents of variables?
Greetings!
The following question arose: It is
required to organize a query to the database based on variables, more precisely, on the presence of data in them. That is, in pure Python and SQL, I would do something like this:
# Есть переменные a, b, c, их содержимое получаю через POST запрос
sql_query = """
SELECT
some_field
FROM
some_table
WHERE
a = '%s'
""" % a
if b:
sql_query += """
AND
b = '%s'
""" % b
if c:
sql_query += """
AND
c = '%s'
""" % c
sql_cursor.execute(sql_query)
# и т.д.
Answer the question
In order to leave comments, you need to log in
num = 1
num2 = 1
if num:
q1 = Q(account_id=num)
else:
q1 = Q()
if num2:
q2 = Q(id=num2)
else:
q2=Q()
numbers = Number.objects.filter(q1|q2)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question