Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SQL from Django QuerySet with filter parameters properly quoted?

Tags:

django

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)
like image 666
serg Avatar asked Dec 24 '22 08:12

serg


1 Answers

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)
like image 156
serg Avatar answered May 26 '23 21:05

serg