Skip to content

Commit 48b9795

Browse files
committed
Check that manually setting Sequence Field in DynamicDocument doesn't increment the counter
Fixes #2471
1 parent af3d3b7 commit 48b9795

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

mongoengine/base/document.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def __setattr__(self, name, value):
156156
# Handle dynamic data only if an initialised dynamic document
157157
if self._dynamic and not self._dynamic_lock:
158158

159-
if not hasattr(self, name) and not name.startswith("_"):
159+
if name not in self._fields_ordered and not name.startswith("_"):
160160
DynamicField = _import_class("DynamicField")
161161
field = DynamicField(db_field=name, null=True)
162162
field.name = name

tests/fields/test_sequence_field.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,25 @@ class Bar(Base):
274274
assert foo.counter == bar.counter
275275
assert foo._fields["counter"].owner_document == Foo
276276
assert bar._fields["counter"].owner_document == Bar
277+
278+
def test_sequence_setattr_not_incrementing_counter(self):
279+
class Person(DynamicDocument):
280+
id = SequenceField(primary_key=True)
281+
name = StringField()
282+
283+
self.db["mongoengine.counters"].drop()
284+
Person.drop_collection()
285+
286+
for x in range(10):
287+
Person(name="Person %s" % x).save()
288+
289+
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
290+
assert c["next"] == 10
291+
292+
# Setting SequenceField field value should not increment counter:
293+
new_person = Person()
294+
new_person.id = 1100
295+
296+
# Counter should still be at 10
297+
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
298+
assert c["next"] == 10

0 commit comments

Comments
 (0)