[Django]-Django raw SQL query – looping over result, it executes a query for every iteration

4👍

Edit:

The issue breaks down here to how Django’s raw() method works. It returns model instances (which had properties you were accessing, resulting in the extra query).

The proper tools here are connection.cursor(), cursor.execute() and cursor.fetchall(). Here’s the example from the docs:

def my_custom_sql():
    from django.db import connection, transaction
    cursor = connection.cursor()

    # Data modifying operation - commit required
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
    transaction.commit_unless_managed()

    # Data retrieval operation - no commit required
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchone()

    return row

http://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly

Leave a comment