2
0
Fork 0

feat: add dict-like behavior to model class instances

This commit is contained in:
Lance Edgar 2024-08-11 15:23:14 -05:00
parent 82c043fd05
commit 08689f494f
2 changed files with 28 additions and 1 deletions

View file

@ -46,7 +46,25 @@ naming_convention = {
metadata = sa.MetaData(naming_convention=naming_convention) metadata = sa.MetaData(naming_convention=naming_convention)
Base = orm.declarative_base(metadata=metadata)
class ModelBase:
""" """
def __iter__(self):
# nb. we override this to allow for `dict(self)`
state = sa.inspect(self)
fields = [attr.key for attr in state.attrs]
return iter([(field, getattr(self, field))
for field in fields])
def __getitem__(self, key):
# nb. we override this to allow for `x = self['field']`
state = sa.inspect(self)
if hasattr(state.attrs, key):
return getattr(self, key)
Base = orm.declarative_base(metadata=metadata, cls=ModelBase)
def uuid_column(*args, **kwargs): def uuid_column(*args, **kwargs):

View file

@ -10,6 +10,15 @@ except ImportError:
pass pass
else: else:
class TestModelBase(TestCase):
def test_dict_behavior(self):
setting = model.Setting()
self.assertEqual(list(iter(setting)), [('name', None), ('value', None)])
self.assertIsNone(setting['name'])
setting.name = 'foo'
self.assertEqual(setting['name'], 'foo')
class TestUUIDColumn(TestCase): class TestUUIDColumn(TestCase):
def test_basic(self): def test_basic(self):