From 758180e7cc369b2ca5eebf1237e13a0725a976aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norman=20J=C3=A4ckel?= Date: Wed, 24 Feb 2016 10:27:42 +0100 Subject: [PATCH] Optimized number of queries for motion serializing. Fixed #1655. --- openslides/motions/serializers.py | 21 +++++++++++++++------ tests/integration/motions/test_viewset.py | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/openslides/motions/serializers.py b/openslides/motions/serializers.py index 0474b23ae..6808d9247 100644 --- a/openslides/motions/serializers.py +++ b/openslides/motions/serializers.py @@ -120,25 +120,34 @@ class MotionPollSerializer(ModelSerializer): def get_yes(self, obj): try: - result = obj.get_votes().get(value='Yes').weight - except obj.get_vote_class().DoesNotExist: + result = self.get_votes_dict(obj)['Yes'] + except KeyError: result = None return result def get_no(self, obj): try: - result = obj.get_votes().get(value='No').weight - except obj.get_vote_class().DoesNotExist: + result = self.get_votes_dict(obj)['No'] + except KeyError: result = None return result def get_abstain(self, obj): try: - result = obj.get_votes().get(value='Abstain').weight - except obj.get_vote_class().DoesNotExist: + result = self.get_votes_dict(obj)['Abstain'] + except KeyError: result = None return result + def get_votes_dict(self, obj): + try: + votes_dict = self._votes_dict + except AttributeError: + votes_dict = self._votes_dict = {} + for vote in obj.get_votes(): + votes_dict[vote.value] = vote.weight + return votes_dict + def get_has_votes(self, obj): """ Returns True if this poll has some votes. diff --git a/tests/integration/motions/test_viewset.py b/tests/integration/motions/test_viewset.py index aa02f9163..f91b193da 100644 --- a/tests/integration/motions/test_viewset.py +++ b/tests/integration/motions/test_viewset.py @@ -136,6 +136,24 @@ class CreateMotion(TestCase): self.assertEqual(response.status_code, status.HTTP_201_CREATED) +class RetrieveMotion(TestCase): + """ + Tests retrieving a motion (with poll results). + """ + def setUp(self): + self.client = APIClient() + self.client.login(username='admin', password='admin') + self.motion = Motion( + title='test_title_uj5eeSiedohSh3ohyaaj', + text='test_text_ithohchaeThohmae5aug') + self.motion.save() + self.motion.create_poll() + + def test_number_of_queries(self): + with self.assertNumQueries(17): + self.client.get(reverse('motion-detail', args=[self.motion.pk])) + + class UpdateMotion(TestCase): """ Tests updating motions.