django mysql 游标,从Django的RawQuerySet获取数据库游标

I have a sizable table (20M+) in Postgres am I try to do a raw Django query on it:

tweets = TweetX.objects.raw("SELECT * from twitter_tweet").using("twittertest")

I get a RawQuerySet fast, but when I try to iterate over its results it is grinding to a halt:

for tweet in tweets:

#do stuff

Memory is steadily rising so I suspect the whole dataset is being transferred.

Is there a way to get a database cursor from .raw so I can iterate over the result set without transferring it all at once?

解决方案

It seems that it is rather difficult to persuade django/postgres to use database cursors. Instead it fetches everything and then put a client side iterator (called cursor) over it.

Found a solution over here that explicitly creates a db cursor. Only downside is it does not fit into django models anymore.

from django.db import connections

conn = connections['twittertest']

# This is required to populate the connection object properly

if conn.connection is None:

cursor = conn.cursor()

cursor = conn.connection.cursor(name='gigantic_cursor')

cursor.execute("SELECT * from twitter_tweet")

for tweet in cursor:

#profit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值