假设我的django应用程序(webapp)中的文件models.py如下所示:
from django.db import models
from django.db import connection
class Foo(models.Model):
name = models.CharField(...)
surname = models.CharField(...)
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
def get_foo():
cursor = connection.cursor()
cursor.execute('SELECT * FROM foo_table')
rows = dictfetchall(cursor)
return rows
要访问我的数据库内容,我基本上有两种选择:
选项1 :
from webapp.models import Foo
bar = Foo.objects.raw('SELECT * FROM foo_table')
选项 2:
from application.models import get_foo
bar = get_foo()
哪个选项执行速度最快?有没有更好的方法来做我想做的事?