A
A
aLap2021-09-13 16:07:06
Django
aLap, 2021-09-13 16:07:06

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)

# и т.д.


Is it possible to do something similar from a django model?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2021-09-13
@aLap

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 question

Ask a Question

731 491 924 answers to any question