From 1b6670dd590ef8f235166ce966d28ac49f322c54 Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Tue, 26 Apr 2011 11:28:50 +0000 Subject: [PATCH] Fixed #15904 - render_comment_form executes unnecessary query for object Thanks to stefanw for report and patch! git-svn-id: http://code.djangoproject.com/svn/django/trunk@16103 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- .../contrib/comments/templatetags/comments.py | 17 ++++++++++++++--- .../comment_tests/tests/templatetag_tests.py | 5 +++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/django/contrib/comments/templatetags/comments.py b/django/contrib/comments/templatetags/comments.py index 42691c63e459b..8bc61cd44565a 100644 --- a/django/contrib/comments/templatetags/comments.py +++ b/django/contrib/comments/templatetags/comments.py @@ -122,12 +122,23 @@ class CommentFormNode(BaseCommentNode): """Insert a form for the comment model into the context.""" def get_form(self, context): - ctype, object_pk = self.get_target_ctype_pk(context) - if object_pk: - return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk)) + obj = self.get_object(context) + if obj: + return comments.get_form()(obj) else: return None + def get_object(self, context): + if self.object_expr: + try: + return self.object_expr.resolve(context) + except template.VariableDoesNotExist: + return None + else: + object_pk = self.object_pk_expr.resolve(context, + ignore_failures=True) + return self.ctype.get_object_for_this_type(pk=object_pk) + def render(self, context): context[self.as_varname] = self.get_form(context) return '' diff --git a/tests/regressiontests/comment_tests/tests/templatetag_tests.py b/tests/regressiontests/comment_tests/tests/templatetag_tests.py index 4c90d9d208bf3..0ead6c2257a63 100644 --- a/tests/regressiontests/comment_tests/tests/templatetag_tests.py +++ b/tests/regressiontests/comment_tests/tests/templatetag_tests.py @@ -40,6 +40,11 @@ def testRenderCommentFormFromLiteral(self): def testRenderCommentFormFromObject(self): self.testRenderCommentForm("{% render_comment_form for a %}") + def testRenderCommentFormFromObjectWithQueryCount(self): + def test(): + self.testRenderCommentFormFromObject() + self.assertNumQueries(1, test) + def testGetCommentCount(self, tag=None): self.createSomeComments() t = "{% load comments %}" + (tag or "{% get_comment_count for comment_tests.article a.id as cc %}") + "{{ cc }}"