0

I use Django ORM to create complex SQL queries dynamically, I want to save ---while running--- the SQL query that Django builds for future use, I have not found a proper way to do it.

As explained here there are two ways to access a query but only connection.queries contains a valid query, and needed to set debug=True.

Because I want to do it in the product environment, debug=True is not really a solution for me, and I don't want to change the Django source code.

Any solution/comment can help me.

I use Django 2.2.

Wouter
  • 534
  • 3
  • 14
  • 22
shimol10
  • 1
  • 1

1 Answers1

0

The answer depends on how you want to save and re-use these queries.

If you want to store/use the queries outside the Django application, I would recommend changing the logging settings, for example, as done here. See also the documentation. If necessary, the logging could also be done at the SQL database itself rather than in Django.

Saving and re-using queries inside the Django application seems to be tricky, and there are security reasons why the connection.queries only works in debug environments. One could try a similar approach as laid out here.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Wouter
  • 534
  • 3
  • 14
  • 22
  • Thanks for your response. I want to save the query in db, it seems that the RequireDebugFalse setting is not useful because Django writes the query to the log only in case 'debug=true', please correct me if I am wrong. Another point is that I need to save the query in the DB with parameters sent in the http request, so I'm not sure if a log can help. – shimol10 Oct 04 '21 at 11:58
  • Then I would suggest an approach as mentioned [here](https://code.djangoproject.com/ticket/17741#comment:4), to get the full query with parameters filled in. – Wouter Oct 04 '21 at 12:53