Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

InsertQuery will respect default field values on model instances when

those values are not specified explicitly -- fixes #107
  • Loading branch information...
commit c102866375f9b8ad823939f92051137a766ec5e8 1 parent 506ecff
@coleifer authored
Showing with 21 additions and 6 deletions.
  1. +14 −6 peewee.py
  2. +7 −0 tests.py
View
20 peewee.py
@@ -1805,7 +1805,9 @@ def execute(self):
class InsertQuery(BaseQuery):
def __init__(self, _model, **kwargs):
- self.insert_query = kwargs
+ query = _model._meta.get_default_dict()
+ query.update(kwargs)
+ self.insert_query = query
super(InsertQuery, self).__init__(_model)
def parse_insert(self):
@@ -2511,6 +2513,15 @@ def prepared(self):
if field.default is not None:
self.defaults[field.name] = field.default
+ def get_default_dict(self):
+ dd = {}
+ for field_name, default in self.defaults.items():
+ if callable(default):
+ dd[field_name] = default()
+ else:
+ dd[field_name] = default
+ return dd
+
def get_sorted_fields(self):
return sorted(self.fields.items(), key=lambda (k,v): (k == self.pk_name and 1 or 2, v._order))
@@ -2654,11 +2665,8 @@ def __init__(self, *args, **kwargs):
setattr(self, k, v)
def initialize_defaults(self):
- for field_name, default in self._meta.defaults.items():
- if callable(default):
- val = default()
- else:
- val = default
+ dd = self._meta.get_default_dict()
+ for field_name, val in dd.items():
setattr(self, field_name, val)
def prepared(self):
View
7 tests.py
@@ -654,6 +654,13 @@ def test_insert(self):
self.assertSQLEqual(iq.sql(), ('INSERT INTO `blog` (`title`) VALUES (?)', ['b']))
self.assertEqual(iq.execute(), 2)
+ # test inserting with defaults, references #107
+ iq = User.insert(username='foo')
+ self.assertSQLEqual(iq.sql(), ('INSERT INTO `users` (`active`,`username`) VALUES (?,?)', [False, 'foo']))
+
+ iq = InsertQuery(User, username='foo')
+ self.assertSQLEqual(iq.sql(), ('INSERT INTO `users` (`active`,`username`) VALUES (?,?)', [False, 'foo']))
+
def test_update(self):
iq = InsertQuery(Blog, title='a').execute()
Please sign in to comment.
Something went wrong with that request. Please try again.