Fixed #27172 -- Closed database cursor explicitly in two doc examples

This commit is contained in:
Chris Jerdonek 2016-09-07 03:14:29 -07:00 committed by Claude Paroz
parent 6a2af01452
commit ccf7adb064
2 changed files with 16 additions and 18 deletions

View File

@ -67,18 +67,18 @@ returns a list of all ``OpinionPoll`` objects, each with an extra
class PollManager(models.Manager): class PollManager(models.Manager):
def with_counts(self): def with_counts(self):
from django.db import connection from django.db import connection
cursor = connection.cursor() with connection.cursor() as cursor:
cursor.execute(""" cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*) SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id WHERE p.id = r.poll_id
GROUP BY p.id, p.question, p.poll_date GROUP BY p.id, p.question, p.poll_date
ORDER BY p.poll_date DESC""") ORDER BY p.poll_date DESC""")
result_list = [] result_list = []
for row in cursor.fetchall(): for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2]) p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3] p.num_responses = row[3]
result_list.append(p) result_list.append(p)
return result_list return result_list
class OpinionPoll(models.Model): class OpinionPoll(models.Model):

View File

@ -250,12 +250,10 @@ For example::
from django.db import connection from django.db import connection
def my_custom_sql(self): def my_custom_sql(self):
cursor = connection.cursor() with connection.cursor() as cursor:
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row return row