Permalink
Browse files

Implementing the "first" method, but implementing it more efficiently so

it will use the query result wrapper
  • Loading branch information...
1 parent 6de84b7 commit 486a08ce6c1592653fba196cee8f7cb523d28d19 @coleifer committed Jan 25, 2013
Showing with 48 additions and 0 deletions.
  1. +8 −0 peewee.py
  2. +40 −0 tests.py
View
@@ -1333,6 +1333,14 @@ def get(self):
raise self.model_class.DoesNotExist('instance matching query does not exist:\nSQL: %s\nPARAMS: %s' % (
self.sql()
))
+
+ def first(self):
+ res = self.execute()
+ res.fill_cache(1)
+ try:
+ return res._result_cache[0]
+ except IndexError:
+ pass
def sql(self):
return self.compiler().generate_select(self)
View
@@ -1054,6 +1054,46 @@ def test_get_or_create(self):
self.assertEqual(u1.id, u1_x.id)
self.assertEqual(User.select().count(), 1)
+ def test_first(self):
+ users = self.create_users(5)
+ qc = len(self.queries())
+
+ sq = User.select().order_by(User.username)
+ qr = sq.execute()
+
+ # call it once
+ first = sq.first()
+ self.assertEqual(first.username, 'u1')
+
+ # check the result cache
+ self.assertEqual(len(qr._result_cache), 1)
+
+ # call it again and we get the same result, but not an
+ # extra query
+ self.assertEqual(sq.first().username, 'u1')
+
+ qc2 = len(self.queries())
+ self.assertEqual(qc2 - qc, 1)
+
+ usernames = [u.username for u in sq]
+ self.assertEqual(usernames, ['u1', 'u2', 'u3', 'u4', 'u5'])
+
+ qc3 = len(self.queries())
+ self.assertEqual(qc3, qc2)
+
+ # call after iterating
+ self.assertEqual(sq.first().username, 'u1')
+
+ usernames = [u.username for u in sq]
+ self.assertEqual(usernames, ['u1', 'u2', 'u3', 'u4', 'u5'])
+
+ qc3 = len(self.queries())
+ self.assertEqual(qc3, qc2)
+
+ # call it with an empty result
+ sq = User.select().where(User.username == 'not-here')
+ self.assertEqual(sq.first(), None)
+
def test_deleting(self):
u1 = self.create_user('u1')
u2 = self.create_user('u2')

0 comments on commit 486a08c

Please sign in to comment.