Skip to content
This repository
Browse code

Adding get_or_create and fixing problem with missing get

  • Loading branch information...
commit 1373f68025c18b09cd20958057a8616db2f8585d 1 parent 73c4fbc
Charles Leifer authored October 02, 2012

Showing 2 changed files with 16 additions and 2 deletions. Show diff stats Hide diff stats

  1. 12  peewee.py
  2. 6  tests.py
12  peewee.py
@@ -1291,8 +1291,8 @@ def get(self):
1291 1291
             obj = clone.execute().next()
1292 1292
             return obj
1293 1293
         except StopIteration:
1294  
-            raise self.model.DoesNotExist('instance matching query does not exist:\nSQL: %s\nPARAMS: %s' % (
1295  
-                query.sql()
  1294
+            raise self.model_class.DoesNotExist('instance matching query does not exist:\nSQL: %s\nPARAMS: %s' % (
  1295
+                self.sql(self.database.get_compiler())
1296 1296
             ))
1297 1297
 
1298 1298
     def sql(self, compiler):
@@ -1868,6 +1868,14 @@ def get(cls, query=None, **kwargs):
1868 1868
         return sq.get()
1869 1869
 
1870 1870
     @classmethod
  1871
+    def get_or_create(cls, **kwargs):
  1872
+        sq = cls.select().filter(**kwargs)
  1873
+        try:
  1874
+            return sq.get()
  1875
+        except cls.DoesNotExist:
  1876
+            return cls.create(**kwargs)
  1877
+
  1878
+    @classmethod
1871 1879
     def table_exists(cls):
1872 1880
         return cls._meta.db_table in cls._meta.database.get_tables()
1873 1881
 
6  tests.py
@@ -803,6 +803,12 @@ def test_reading(self):
803 803
         self.assertEqual(u1, User.get(User.username == 'u1'))
804 804
         self.assertEqual(u2, User.get(User.username == 'u2'))
805 805
 
  806
+    def test_get_or_create(self):
  807
+        u1 = User.get_or_create(username='u1')
  808
+        u1_x = User.get_or_create(username='u1')
  809
+        self.assertEqual(u1.id, u1_x.id)
  810
+        self.assertEqual(User.select().count(), 1)
  811
+
806 812
     def test_deleting(self):
807 813
         u1 = self.create_user('u1')
808 814
         u2 = self.create_user('u2')

0 notes on commit 1373f68

Please sign in to comment.
Something went wrong with that request. Please try again.