Django原始SQL查询 - 循环结果,它为每次迭代执行一个查询 [英] Django raw SQL query - looping over result, it executes a query for every iteration

查看:122
本文介绍了Django原始SQL查询 - 循环结果,它为每次迭代执行一个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在注意到Django的内置查询的效率低下之后,写了一些原始的SQL查询。我试图通过 QuerySet 结果循环,并将它们分组(我知道重组模板标签,这对我来说不起作用 - 我需要能够独立访问单独的组)。这是我的代码:

  m = Media.objects.raw('SELECT * FROM table')#查询简化为了示例

media_items = {'aim-icons':[],'banners':[],'hi-res-photos':[],'照片':[],'print-ads' :[],'影片':[],'壁纸':[]}

对于m中的项目:
media_items [item.type_slug] .append(item)

这给了我所需要的(例如我可以访问的列表,如 media_items ['wallpaper '] ),但它为每次迭代运行数据库查询以获取 type_slug 字段。我尝试在循环之前添加 m = list(m)。没有任何效果。



任何人都可以帮助我?这个看起来应该很简单。



谢谢,
Matt

解决方案

编辑:



这个问题分解了Django的 raw()方法的工作原理。它返回模型实例(具有您正在访问的属性,导致额外的查询)。



这里正确的工具是 connection.cursor() cursor.execute() cursor.fetchall()。以下是文档中的示例:

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

#数据修改操作 - 提交必需
cursor.execute(UPDATE bar SET foo = 1 WHERE baz =%s,[self.baz])
transaction.commit_unless_managed()

#数据检索操作 - 不需要提交
cursor.execute(SELECT foo FROM bar WHERE baz =%s,[self.baz] )
row = cursor.fetchone()

返回行

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


Been writing some raw SQL queries after noticing how inefficient some of Django's built-in queries were. I'm trying to loop through the QuerySet result and group them into categories (I'm aware of the regroup template tag, this doesn't work for me - I need to be able to access the separate groups independently). Here's 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 (eg a list that I can access like media_items['wallpapers']) but it runs a database query for every iteration to fetch the type_slug field. I tried adding m = list(m) before the loop, no effect.

Can anyone help me out here? This seems like it should be simple.

Thanks, Matt

解决方案

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

这篇关于Django原始SQL查询 - 循环结果,它为每次迭代执行一个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆