SELECT INTO with a QuerySet

My team’s running large aggregations queries in our Postgres database, the result of which don’t need to be retrieved immediately.
Since we want to avoid creating model instances we don’t need for upwards of 500k result rows and, instead, retrieve the results later, we’ve decided to use the SELECT INTO feature of postgres which stores the result of the query in a temporary table and does not return anything to the Django app.

So far we’ve only managed to manually write these queries using the .raw() method of a queryset as we couldn’t find a way to implement SELECT INTO with the QuerySet API. I’d like to us to use a queryset instead to reduce security risks and improve maintainability.

Is there a way to implement a SELECT INTO query using the queryset api that we’ve missed? Has anyone attempted something similar before?

Thanks!

1 Like

Hmmm… Interesting idea, but I don’t see how it ties into the idea of a Django queryset at all. A queryset is a Python representation of an SQL resultset, which is not returned by PostgreSQL from a “SELECT INTO” command.

Even though it uses the “SELECT” verb, my opinion is that “SELECT INTO” would be more categorized as DDL rather than DML (or DQL if you’re so inclined).
Note that the ORM doesn’t handle other DDL such as “CREATE TABLE”, etc, either.

So no, I don’t think you’re going to find any option within the ORM to support that command.