Merge pull request #2000 from normanjaeckel/VotesQuery

Optimized number of queries for motion serializing. Fixed #1655.
This commit is contained in:
Emanuel Schütze 2016-02-24 11:10:11 +01:00
commit 88b2e8a73e
2 changed files with 33 additions and 6 deletions

View File

@ -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.

View File

@ -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.