6
MyModel.objects.filter(name="my name", date__lte=datetime.now()).query

Outputs:

SELECT "mymodel"."id", "mymodel"."name", "mymodel"."date" 
FROM "mymodel" 
WHERE ("mymodel"."name" = my name AND "mymodel"."date" <= 2016-02-24 20:24:00.456974+00:00)

Which is not a valid SQL (filter parameters are unquoted).

How can I get the exact SQL that will be executed, which is:

SELECT "mymodel"."id", "mymodel"."name", "mymodel"."date" 
FROM "mymodel" 
WHERE ("mymodel"."name" = 'my name' AND "mymodel"."date" <= '2016-02-24 20:24:00.456974+00:00'::timestamptz)

1 Answer 1

12

This isn't fully answering it, but for my purposes I wanted to be able to rerun the query as raw sql. I was able to get sql and params using:

queryset = MyModel.objects.filter(name="my name", date__lte=datetime.now())
sql, sql_params = queryset.query.get_compiler(using=queryset.db).as_sql()

Then I could use these values to rerun the query as raw:

MyModel.objects.raw(sql, sql_params)
Sign up to request clarification or add additional context in comments.

2 Comments

Dude you saved me hours of torture, I did not know about the get_compiler method, i was queryset.query.__str__() and going to the dark side of regex since Django was not escaping the parameters when you invoice str like that
I don't know from which Django version, but it could be more simplified to queryset.query.sql_with_params()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.