Permalink
Browse files

Merge branch 'respect-fields-order-when-creating' into related_fields

  • Loading branch information...
2 parents 71f1116 + d5b45fb commit c643d77a43815af006d86ae11dfadbaeb12edb1c @twidi committed Aug 11, 2012
Showing with 21 additions and 4 deletions.
  1. +17 −4 limpyd/model.py
  2. +4 −0 tests/model.py
View
@@ -90,6 +90,10 @@ def __new__(mcs, name, base, attrs):
if isinstance(field, HashableField):
_hashable_fields.append(field.name)
+ # keep the pk as first field
+ _fields.remove(pk_field.name)
+ _fields.insert(0, pk_field.name)
+
# Save usefull attributes on the final model
setattr(it, "_fields", _fields)
setattr(it, "_hashable_fields", _hashable_fields)
@@ -154,8 +158,13 @@ def __init__(self, *args, **kwargs):
# (More robust than trying to manage a "pseudotransaction", as
# redis do not has "real" transactions)
# Here we do not set anything, in case one unique field fails
+ kwargs_pk_field_name = None
for field_name, value in kwargs.iteritems():
- if field_name == 'pk':
+ if self._field_is_pk(field_name):
+ if kwargs_pk_field_name:
+ raise ValueError(u'You cannot pass two values for the '
+ 'primary key (pk and %s)' % pk_field_name)
+ kwargs_pk_field_name = field_name
# always use the real field name, not always pk
field_name = pk_field_name
if field_name not in self._fields:
@@ -166,10 +175,14 @@ def __init__(self, *args, **kwargs):
raise UniquenessError(u"Field `%s` must be unique. "
"Value `%s` yet indexed." % (field.name, value))
- # Do instanciate
- for field_name, value in kwargs.iteritems():
+ # Do instanciate, starting by the pk and respecting fields order
+ if kwargs_pk_field_name:
+ self.pk.set(kwargs[kwargs_pk_field_name])
+ for field_name in self._fields:
+ if field_name not in kwargs or self._field_is_pk(field_name):
+ continue
field = getattr(self, field_name)
- field.proxy_set(value)
+ field.proxy_set(kwargs[field_name])
# --- Instanciate from DB
if len(args) == 1:
View
@@ -552,6 +552,10 @@ def test_can_access_pk_with_two_names(self):
self.assertEqual(set(self.RedefinedNotAutoPkField.collection(pk=1)), set(['1', ]))
self.assertEqual(set(self.RedefinedNotAutoPkField.collection(id=2)), set(['2', ]))
+ def test_cannot_set_pk_with_two_names(self):
+ with self.assertRaises(ValueError):
+ self.RedefinedNotAutoPkField(name="foo", pk=1, id=2)
+
class DeleteTest(LimpydBaseTest):

0 comments on commit c643d77

Please sign in to comment.