Skip to content

Commit 8795c14

Browse files
committed
Fixed F() updates w/ custom db_column + light refactoring in the area.
Thanks to Michael Jung for the report! Closes #87.
1 parent a52c90c commit 8795c14

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

django_mongodb_engine/compiler.py

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -423,30 +423,31 @@ def update(self, values):
423423
multi = True
424424
spec = {}
425425
for field, value in values:
426+
if field.primary_key:
427+
raise DatabaseError("Can not modify _id")
426428
if getattr(field, 'forbids_updates', False):
427429
raise DatabaseError("Updates on %ss are not allowed" %
428430
field.__class__.__name__)
429-
if field.unique:
430-
multi = False
431-
if hasattr(value, "evaluate"):
432-
assert value.connector in (value.ADD, value.SUB)
433-
assert not value.negated
434-
assert not value.subtree_parents
431+
if hasattr(value, 'evaluate'):
432+
# .update(foo=F('foo') + 42) --> {'$inc': {'foo': 42}}
435433
lhs, rhs = value.children
436-
if isinstance(lhs, F):
437-
assert not isinstance(rhs, F)
438-
assert lhs.name == field.name
439-
if value.connector == value.SUB:
440-
rhs = -rhs
441-
else:
442-
assert value.connector == value.ADD
443-
rhs, lhs = lhs, rhs
444-
action, column, value = '$inc', lhs.name, rhs
434+
assert value.connector in (value.ADD, value.SUB) \
435+
and not value.negated \
436+
and not value.subtree_parents \
437+
and isinstance(lhs, F) \
438+
and not isinstance(rhs, F) \
439+
and lhs.name == field.name
440+
if value.connector == value.SUB:
441+
rhs = -rhs
442+
action = '$inc'
443+
value = rhs
445444
else:
446-
action, column, value = '$set', field.column, value
447-
if column == get_pk_column(self):
448-
raise DatabaseError("Can not modify _id")
449-
spec.setdefault(action, {})[column] = value
445+
# .update(foo=123) --> {'$set': {'foo': 123}}
446+
action = '$set'
447+
spec.setdefault(action, {})[field.column] = value
448+
449+
if field.unique:
450+
multi = False
450451

451452
return self.execute_update(spec, multi)
452453

0 commit comments

Comments
 (0)