Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adding get_or_create and fixing problem with missing get

  • Loading branch information...
commit 1373f68025c18b09cd20958057a8616db2f8585d 1 parent 73c4fbc
Charles Leifer authored
Showing with 16 additions and 2 deletions.
  1. +10 −2 peewee.py
  2. +6 −0 tests.py
12 peewee.py
View
@@ -1291,8 +1291,8 @@ def get(self):
obj = clone.execute().next()
return obj
except StopIteration:
- raise self.model.DoesNotExist('instance matching query does not exist:\nSQL: %s\nPARAMS: %s' % (
- query.sql()
+ raise self.model_class.DoesNotExist('instance matching query does not exist:\nSQL: %s\nPARAMS: %s' % (
+ self.sql(self.database.get_compiler())
))
def sql(self, compiler):
@@ -1868,6 +1868,14 @@ def get(cls, query=None, **kwargs):
return sq.get()
@classmethod
+ def get_or_create(cls, **kwargs):
+ sq = cls.select().filter(**kwargs)
+ try:
+ return sq.get()
+ except cls.DoesNotExist:
+ return cls.create(**kwargs)
+
+ @classmethod
def table_exists(cls):
return cls._meta.db_table in cls._meta.database.get_tables()
6 tests.py
View
@@ -803,6 +803,12 @@ def test_reading(self):
self.assertEqual(u1, User.get(User.username == 'u1'))
self.assertEqual(u2, User.get(User.username == 'u2'))
+ def test_get_or_create(self):
+ u1 = User.get_or_create(username='u1')
+ u1_x = User.get_or_create(username='u1')
+ self.assertEqual(u1.id, u1_x.id)
+ self.assertEqual(User.select().count(), 1)
+
def test_deleting(self):
u1 = self.create_user('u1')
u2 = self.create_user('u2')
Please sign in to comment.
Something went wrong with that request. Please try again.