Django raw SQL query - a circular result, it executes a query for each iteration

Wrote some raw SQL queries, noticing how inefficient some of Django's built-in queries are. I am trying to loop QuerySetand group them into categories (I know the template tag regroup, this does not work for me - I need to be able to access individual groups independently), Here is my code:

m = Media.objects.raw('SELECT * FROM table') # query simplified for sake of example

media_items = {'aim-icons' : [], 'banners' : [], 'hi-res-photos' : [], 'photos' : [], 'print-ads' : [], 'videos' : [], 'wallpapers' : [] }

for item in m:
    media_items[item.type_slug].append(item)

This gives me what I want (for example, a list that I can access, for example media_items['wallpapers']), but it runs a database query for each iteration to get the field type_slug. I tried adding m = list(m)before the loop, without effect.

Can anyone help me here? It seems to be easy.

Thanks Matt

+3
1

Edit:

, Django raw(). ( , , ).

connection.cursor(), cursor.execute() cursor.fetchall(). :

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

+4

All Articles