Django 原始 SQL 查询 - 循环结果,它为每次迭代执行一个查询
在注意到 Django 的一些内置查询效率低下后,我开始编写一些原始 SQL 查询。我正在尝试循环遍历 QuerySet
结果并将它们分组(我知道 regroup
模板标记,这对我不起作用 - 我需要能够独立访问不同的组)。这是我的代码:
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)
这给了我想要的东西(例如,我可以像 media_items['wallpapers']
一样访问的列表),但它为每次迭代运行数据库查询以获取 type_slug< /代码> 字段。我尝试在循环之前添加
m = list(m)
,但没有效果。
有人可以帮我吗?这看起来应该很简单。
谢谢, 马特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
问题在这里分解为 Django 的
raw()
方法如何工作。它返回模型实例(其中具有您正在访问的属性,导致额外的查询)。这里合适的工具是
connection.cursor()
、cursor.execute()
和cursor.fetchall()
。这是文档中的示例:http:// /docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly
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()
andcursor.fetchall()
. Here's the example from the docs:http://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly