mirror of
https://github.com/internetarchive/warcprox.git
synced 2025-01-18 13:22:09 +01:00
new method on orm class populate_defaults(), which runs at the beginning of save(), since populating them in __init__() is problematic
This commit is contained in:
parent
07bc01cbbd
commit
3fd2e5cf60
@ -51,7 +51,7 @@ Usage Example
|
||||
doc1 = MyTable(rr, {'animal': 'elephant', 'size': 'large'})
|
||||
doc1.save()
|
||||
|
||||
doc1_copy = MyTable.get(rr, doc1.id)
|
||||
doc1_copy = MyTable.load(rr, doc1.id)
|
||||
doc1_copy.food = 'bread'
|
||||
doc1_copy.save()
|
||||
|
||||
|
@ -273,6 +273,14 @@ class Document(dict, object):
|
||||
'''
|
||||
return getattr(self, self.pk_field)
|
||||
|
||||
def populate_defaults(self):
|
||||
'''
|
||||
This method is called by `save()` before persisting the document to
|
||||
the database. Subclasses should override it to populate default values
|
||||
if appropriate.
|
||||
'''
|
||||
pass
|
||||
|
||||
def save(self):
|
||||
'''
|
||||
Persist changes to rethinkdb. Updates only the fields that have
|
||||
@ -285,6 +293,7 @@ class Document(dict, object):
|
||||
touched.
|
||||
'''
|
||||
should_insert = False
|
||||
self.populate_defaults()
|
||||
try:
|
||||
self[self.pk_field] # raises KeyError if missing
|
||||
if self._updates:
|
||||
|
2
setup.py
2
setup.py
@ -3,7 +3,7 @@ import codecs
|
||||
|
||||
setuptools.setup(
|
||||
name='doublethink',
|
||||
version='0.2.0.dev69',
|
||||
version='0.2.0.dev70',
|
||||
packages=['doublethink'],
|
||||
classifiers=[
|
||||
'Programming Language :: Python :: 2.7',
|
||||
|
@ -279,4 +279,27 @@ def test_orm_pk(rr):
|
||||
assert e['blah'] == 'toot'
|
||||
assert e == e_copy
|
||||
|
||||
def test_default_values(rr):
|
||||
class Person(doublethink.Document):
|
||||
def populate_defaults(self):
|
||||
if not "age" in self:
|
||||
self.age = 0 # born today
|
||||
|
||||
Person.table_ensure(rr)
|
||||
p = Person(rr, {})
|
||||
assert not "age" in p
|
||||
assert p.age is None
|
||||
p.save()
|
||||
assert p.age == 0
|
||||
assert p.id
|
||||
|
||||
p.age = 50
|
||||
p.save()
|
||||
|
||||
q = Person.load(rr, p.id)
|
||||
assert q.age == 50
|
||||
q.save()
|
||||
assert q.age == 50
|
||||
q.refresh()
|
||||
assert q.age == 50
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user