Created
January 27, 2018 17:52
-
-
Save toransahu/62cd045891656b90f7e18a492e9b81db to your computer and use it in GitHub Desktop.
Django - Custom Query Manager Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class PollManager(models.Manager): | |
def with_counts(self): | |
from django.db import connection | |
with connection.cursor() as 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 | |
class OpinionPoll(models.Model): | |
question = models.CharField(max_length=200) | |
poll_date = models.DateField() | |
objects = PollManager() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment