I need to use a raw SQL query in a Django app I am writing. The SQL query contains an in
clause in the where
statement:
select *
from abc_mymodel
where some_fk in (1,2,3)
and some_status = 'foo'
I am a big proponent of passing SQL params as parameters. This is easily done for the single value ones. However, I am not sure how (or if) this can be done for in
clauses. Ideally I would like to do something like:
sql = """
select *
from abc_mymodel
where some_fk in %s
and some_status = %s
"""
my_list = [1,2,3]
my_status = 'foo'
trinkets = MyModel.objects.raw(
sql,
params=(my_list, my_status)
)
I know I can use string composition to write the in
clause and use params for the remaining values. However, I am curious if it is possible to use params for in
clauses as well.
According to the Django docs on
raw()
,Conveniently, raw queries are very easy to test in a django shell. If you simply input your
raw()
query, it will print aRawQuerySet
with your resulting query:As you can see, whatever is in
params
is placed into the raw query. In your example, you need to changemy_list
to a tuple (or else it will look like "IN [1,2,3]") and change yourparams
input to a list (params=[my_list, my_status]
).try it this way for django orm type querying :
In your case :