迭代Django查询的结果

2024-05-16 19:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django查询,我需要迭代它的结果,但是它非常慢……下面是一些代码

query = <Model>.objects.filter(<filter settings>

results = rollup(query) #This function isn't super important, it's basically just summing over
#specific fields that have specific properties, emptying the rest, and maintaing a few, the 
#result is still a django query set

现在我想做点什么

^{pr2}$

我尝试过使用类似prefetch_related的方法,但没有看到非常明显的效果。我能对这个查询做些什么改进吗


Tags: thedjango代码modelobjectssettingsfunctionfilter
1条回答
网友
1楼 · 发布于 2024-05-16 19:45:14

由于Django-ORM架构(您应该创建大量Python对象),所以过滤器的速度很慢,因为有大量的结果。在

要么你的要求不好,要么是误解,要么你可以用模型.objects.raw()用于直接SQL查询(在某些情况下更快10倍)。在

您也可以使用connection对象的直接SQL查询,但是您必须自己处理对象的创建(或列表或词法)。我在一个项目中使用这个查询,它比Django-one快60倍,我使用dict(zip(myfieldslist, myresult))来检索与模板兼容的结果。在

参见:https://docs.djangoproject.com/en/1.7/topics/db/sql/

相关问题 更多 >