What makes sense to me is the query builder (ORM) in Django "escapes"/quotes the values at the very last moment: whenever the query is to be executed in a database. Different databases can have different escape characters. When you print queryset.query it simply isn't at a stage where the escape characters have been added. No "default" quoting is happening because Django has no implementation for this: all escaping is off-loaded to the specific database packages if possible (e.g. MySQLdb, psycopg2, sqlite3). Simply put: queryset.query isn't meant to output valid sql as-is, nobody claims as much. In fact, checking the source code actually underlines my point:
https://github.com/django/django/blob/8a281aa7fe76a9da2284f943964a9413697cff1f/django/db/models/sql/query.py#L253-L262 def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params On Tuesday, 20 August 2019 17:43:38 UTC+2, Jo wrote: > > 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? > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0ed2b0cf-f1e1-4bd7-8504-2c99e778c27a%40googlegroups.com.