Printing Django QuerySet SQL with “”

后端 未结 3 780
难免孤独
难免孤独 2021-01-18 01:41

You can print a queryset\'s SQL as follows:

print str(queryset.query)

however, for some reason this removes quotation marks, so you get:

3条回答
  •  独厮守ぢ
    2021-01-18 02:17

    If the underlying database is PostgreSQL you can do:

    from django.db import connection
    sql, params = queryset.query.sql_with_params()
    cursor = connection.cursor()
    cursor.mogrify(sql, params)
    

    sql_with_params returns the plain query without any values substituted and the parameters that will be inserted in the query.

    It is still not recommended to use .mogrify() for other purposes than debugging because the method may disappear in the future.

    If you want to execute the query, you can/should just use .raw().

    YourModel.objects.raw(sql, params)
    

提交回复
热议问题