7

Is it possible to print the SQL made by an queryset.exists() statement in Django?

freyley
  • 4,145
  • 3
  • 20
  • 25
  • 3
    try: http://stackoverflow.com/questions/1074212/show-the-sql-django-is-running – cdvv7788 Feb 06 '15 at 23:19
  • 2
    Or better yet, use this: https://github.com/django-debug-toolbar/django-debug-toolbar Once installed it will show all querys used in a request – cdvv7788 Feb 06 '15 at 23:21

1 Answers1

-4

Usually yes you can print SQL QuerySets generate however since exists() does not return a QuerySet but returns a simple boolean, it is more difficult.

Perhaps the easiest way is not to print SQL query for just exists() but for all queries in the view. You can follow other SO question on how to do that (example) or you can use django-debug-toolbar.


If you are also interesting in printing queries QuerySet generates, you can print a complete SQL query using:

print(Model.objects.filter(...).exists().query)

That will print a complete query.

If your intention however is to be able to copy-paste the query and execute it directly, it might not always work. For example printing the query does not always produce correct syntax such as with dates. There however is another useful method in Django Query objects (which is QuerySet.query is instance of) - sql_with_params(). That returns your parameterized query with the parameters themselves. For example:

sql, params = Model.objects.filter(...).exists().query.sql_with_params()
Model.objects.raw(sql, params=params)
Community
  • 1
  • 1
miki725
  • 27,207
  • 17
  • 105
  • 121
  • 11
    `Model.objects.filter().exists()` will return a boolean value. and accessing .query() on boolean value will give `AttributeError`. or not? – Sarfraz Ahmad Feb 01 '17 at 18:05