Skip to content

Apply defaults to fields with None value at 'set' time. #349

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions mongoengine/base/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ def __get__(self, instance, owner):
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document.
"""
if value is None:
value = self.default
# Allow callable default values
if callable(value):
value = value()

if instance._initialised:
try:
if (self.name not in instance._data or
Expand Down
13 changes: 13 additions & 0 deletions tests/fields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ class Person(Document):
self.assertEqual(person._fields['age'].help_text, "Your real age")
self.assertEqual(person._fields['userid'].verbose_name, "User Identity")

class Person2(Document):
created = DateTimeField(default=datetime.datetime.utcnow)

person = Person2()
date1 = person.created
date2 = person.created
self.assertEqual(date1, date2)

person = Person2(created=None)
date1 = person.created
date2 = person.created
self.assertEqual(date1, date2)

def test_required_values(self):
"""Ensure that required field constraints are enforced.
"""
Expand Down