Skip to content

Commit

Permalink
DateTimeField with auto_now were overwriting...
Browse files Browse the repository at this point in the history
file values during load with tznow()
  • Loading branch information
kneufeld committed Jan 14, 2019
1 parent 97d1359 commit 2bc0a5a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
16 changes: 8 additions & 8 deletions alkali/metamodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,19 +239,19 @@ def __call__(cls, *args, **kw):

# put field values (int,str,etc) into model instance
for name, field in cls.Meta.fields.items():
# THINK: this somewhat duplicates Field.__set__ code
value = kw.pop(name, field.default_value)
if getattr(field, 'auto_now', False):
value = kw.pop(name, tznow().isoformat())
elif getattr(field, 'auto_now_add', False):
value = kw.pop(name, tznow().isoformat())
else:
# THINK: this somewhat duplicates Field.__set__ code
value = kw.pop(name, field.default_value)

value = field.cast(value)

# store the actual value in the model's __dict__, used by Field.__get__
obj.__dict__[name] = value

if getattr(field, 'auto_now_add', False):
obj.__dict__[name] = tznow()

if getattr(field, 'auto_now', False):
obj.__dict__[name] = tznow()

obj._dirty = False
obj.__init__(*args, **kw)

Expand Down
33 changes: 32 additions & 1 deletion alkali/tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import unittest
import mock
import datetime as dt
import json
import tempfile

from alkali.fields import Field
from alkali.fields import IntField, StringField, BoolField
Expand All @@ -12,7 +14,7 @@
from alkali.fields import ForeignKey, OneToOneField
from alkali.model import Model

from . import MyModel, MyMulti, MyDepModel
from . import MyModel, MyMulti, MyDepModel, AutoModel1

class TestField( unittest.TestCase ):

Expand Down Expand Up @@ -382,3 +384,32 @@ class AutoModel1(Model):

with self.assertRaises(RuntimeError):
m.uuid = "abc"

def test_date_load_with_autotime(self):
"""
make sure when we load a record that has auto_now or auto_now_add
that the value in the file is used
"""
tfile = tempfile.NamedTemporaryFile()

data = b"""[{
"auto": 5,
"creation": "2010-01-13T17:52:09.131085-07:00",
"modified": "2010-01-13T17:52:09.131178-07:00",
"f1": "a value",
"f2": null
}]"""

tfile.write(data)
tfile.flush()

creation = dt.datetime.fromisoformat("2010-01-13T17:52:09.131085-07:00")
modified = dt.datetime.fromisoformat("2010-01-13T17:52:09.131178-07:00")

from alkali.storage import JSONStorage
storage = JSONStorage(tfile.name)
AutoModel1.objects.load(storage)
m = AutoModel1.objects.instances[0]

self.assertEqual(creation, m.creation)
self.assertEqual(modified, m.modified)

0 comments on commit 2bc0a5a

Please sign in to comment.