Permalink
Browse files

Fix that allows 0 as a valid integer primary key

  • Loading branch information...
1 parent 25ce523 commit 51328066c4c7b1d7c043c5e37fc06c519e9f168a @coleifer committed Dec 20, 2012
Showing with 16 additions and 4 deletions.
  1. +4 −4 peewee.py
  2. +12 −0 tests.py
View
8 peewee.py
@@ -437,7 +437,7 @@ def __init__(self, field, rel_model):
def get_object_or_id(self, instance):
rel_id = instance._data.get(self.att_name)
- if rel_id or self.att_name in instance._obj_cache:
+ if rel_id is not None or self.att_name in instance._obj_cache:
if self.att_name not in instance._obj_cache:
obj = self.rel_model.get(self.rel_model._meta.primary_key==rel_id)
instance._obj_cache[self.att_name] = obj
@@ -956,7 +956,7 @@ def follow_joins(self, joins, collected_models, current):
if not fk_field:
continue
- if not joined_inst.get_id() and fk_field.name in inst._data:
+ if joined_inst.get_id() is None and fk_field.name in inst._data:
rel_inst_id = inst._data[fk_field.name]
joined_inst.set_id(rel_inst_id)
@@ -1985,7 +1985,7 @@ def prepared(self):
def save(self, force_insert=False):
field_dict = dict(self._data)
pk = self._meta.primary_key
- if self.get_id() and not force_insert:
+ if self.get_id() is not None and not force_insert:
field_dict.pop(pk.name)
update = self.update(
**field_dict
@@ -2026,7 +2026,7 @@ def delete_instance(self, recursive=False, delete_nullable=False):
def __eq__(self, other):
return other.__class__ == self.__class__ and \
- self.get_id() and \
+ self.get_id() is not None and \
other.get_id() == self.get_id()
def __ne__(self, other):
View
12 tests.py
@@ -944,6 +944,18 @@ def test_saving(self):
self.assertEqual(User.select().count(), 1)
+ def test_zero_id(self):
+ query = 'insert into users (id, username) values (%s, %s)' % (
+ test_db.interpolation, test_db.interpolation)
+ test_db.execute_sql(query, (0, 'foo'))
+ Blog.insert(title='foo2', user=0).execute()
+
+ u = User.get(User.id == 0)
+ b = Blog.get(Blog.user == u)
+
+ self.assertTrue(u == u)
+ self.assertTrue(u == b.user)
+
def test_saving_via_create_gh111(self):
u = User.create(username='u')
b = Blog.create(title='foo', user=u)

0 comments on commit 5132806

Please sign in to comment.