Entity
Base usage
You can describe wrappers for data structures with Entity
from corm import Storage, Entity
class User(Entity):
id: int
name: str
description: str = 'cool guy'
storage = Storage()
john = User({'id': 1, 'name': 'John', 'address': 'kirova 1'}, storage)
john.name = 'Not John'
assert john.dict() == {
'id': 1, 'name': 'Not John',
'address': 'kirova 1', 'description': 'cool guy',
}
Note
You don't need to describe full data structure, only fields you need, rest corm leave as is. In example above address
key
Fields
To set additional settings for any entity fields there is Field
class
from corm import Storage, Entity, Field
class User(Entity):
id: int = Field(origin='user_id')
name: str
description: str = Field(default='user')
storage = Storage()
user = User(data={'user_id': 33, 'name': 'John'}, storage=storage)
assert user.id == 33
assert user.description == 'user'
assert user.dict() == {'user_id': 33, 'name': 'John', 'description': 'user'}
Default values
There are two ways to set default value, just set as class value or through default
param of Field
, Nested
or KeyNested
from corm import Storage, Entity, Field
class Foo(Entity):
inplace = 1
in_field = Field(default=2)
in_field_callable = Field(default=list)
storage = Storage()
foo = Foo(data={}, storage=storage)
assert foo.inplace == 1
assert foo.in_field == 2
assert foo.in_field_callable == []
Note
default
also can be callable, corm call it each time when creating entity instance if value of field is not provided. But you can use it only with Field
, Nested
or KeyNested
, inplace is not allowed
from corm import Storage, Entity
class Foo(Entity):
inplace = list
storage = Storage()
foo = Foo(data={}, storage=storage)
assert foo.inplace == list # still callable, not new empty list