Reputation: 877
In terms of performance, which one is better modifying queryset or writing SQL through managers in django?
class DahlBookManager(models.Manager):
def get_queryset(self):
return super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl')
or
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id
GROUP BY p.id, p.question, p.poll_date
ORDER BY p.poll_date DESC""")
result_list = []
for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3]
result_list.append(p)
return result_list
Upvotes: 0
Views: 35
Reputation: 43300
I'd imagine its the first one - but this isn't a fair contest.
Your second pure sql statement also has to do a grouping and an ordering which your first does not so the first is just a WHERE
.
The reason it could be the second is because the first gets *
rather than just the 3 items you need so you may be better off with the following:
super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl').values('id',
'question',
'poll_date')
Now this may just be my opinion but for most queries you do in django you should use django and avoid raw queries. It will help you if you ever decide to use a different database schema and potentially create more efficient queries.
Upvotes: 1