Search code examples
djangopostgresqldjango-orm

Django's str(queryset.query) returns invalid SQL if I compare datetimes


I have a Django queryset that I prepare with queryset.filter(date__gte=datetime(2011,1,1))

If I then call str(queryset.query) I see this in the string:

... WHERE "App_table"."date" >= 2011-1-1

However, this is invalid SQL code as if I run this in Postgresql I get this error:

... WHERE "App_table"."date" >= 2011-1-1
ERROR:  operator does not exist: date >= integer
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Why is this happening and how can I ask Django to output proper SQL code that I can work on?


Solution

  • You can use the query. sql_with_params() method.

    print(q.query. sql_with_params())
    

    This will print a parameterized version of the query.