python - Raw queries and custom sql queries what is the fastest? -
assuming file models.py in django application (webapp) following :
from django.db import models django.db import connection class foo(models.model): name = models.charfield(...) surname = models.charfield(...) def dictfetchall(cursor): "returns rows cursor dict" desc = cursor.description return [ dict(zip([col[0] col in desc], row)) row in cursor.fetchall() ] def get_foo(): cursor = connection.cursor() cursor.execute('select * foo_table') rows = dictfetchall(cursor) return rows
to access database content, have basicly 2 options :
option 1 :
from webapp.models import foo bar = foo.objects.raw('select * foo_table')
option 2 :
from application.models import get_foo bar = get_foo()
which option fastest in execution ? there better way want ?
there no direct , clear answer on approach better.
using manager.raw()
still keeps within orm
layer , while returns model instances still have nice database abstraction. but, while making raw query, django more cursor.execute
in order translate results model instances (see happening in rawqueryset , rawquery classes).
but (quote docs):
sometimes manager.raw() isn’t quite enough: might need perform queries don’t map cleanly models, or directly execute update, insert, or delete queries.
so, speaking, choose depends on results going , going them.
see also:
Comments
Post a Comment