Dictalchemy adds utils.asdict() and utils.fromdict() methods to SQLAlchemy declarative models.
Currently this works with synonyms and simple relationships as one-to-many and many-to-many. Relationships can be followed in many levels.
classes.DictableModel can be used as base class for declarative_base or as a mixin for a declarative class.
Example usage:
from dictalchemy import DictableModel
from slqlachemy.ext.declarative import declarative_base
Base = declarative_base(cls=DictableModel)
This method can be run on existing classes to make them dictable.
Example:
Base = declarative_base()
make_class_dictable(Base)
Default values are defined in dictalchemy.constants.
Any collection that inherits from dict or list is supported together with sqlalchemy.orm.dynamic.AppenderMixin, sqlalchemy.orm.query.Query sqlalchemy.orm.associationproxy._AssociationList and sqlalchemy.orm.associationproxy._AssociationDict.
Simple example:
>>> session.query(User).asdict()
{'id': 1, 'username': 'Gerald'}
Using exclude_pk:
>>> session.query(User).asdict(exclude_pk=True)
{'username': 'Gerald'}
Using exclude:
>>> session.query(User).asdict(exclude=['id'])
{'username': 'Gerald'}
Using follow without arguments:
>>> session.query(User).asdict(follow={'groups':{}})
{'username': 'Gerald', groups=[{'id': 1, 'name': 'User'}]}
Using follow with arguments:
>>> session.query(User).asdict(follow={'groups':{'exclude': ['id']})
{'username': 'Gerald', groups=[{'name': 'User'}]}
Using follow with a parent argument:
>>> session.query(User).asdict(follow={'groups':{'parent': 'relationships', 'exclude': ['id']})
{'username': 'Gerald', 'relationships': {'groups':[{'name': 'User'}]}}
Using include(for example for including synonyms/properties):
>>> session.query(User).asdict(include=['displayname']
{'id': 1, 'username': 'Gerald', 'displayname': 'Gerald'}
Note
New in v 0.1.2.1
The argument method is used to determine which method asdict should call when following relations. If method is set in the follow arguments that method will be used instead. See the HAL example in dictalchemy.utils.asdict().
Without arguments:
>>> user = session.query(User).first()
>>> dict(user)
{'id': 3, 'name': 'Gerald'}
>>> user.fromdict({'name': 'Gerald the Great'})
>>> dict(user)
{'name': 'Gerald the Great'}
Excluding underscore:
>>> user = session.query(User).first()
>>> dict(user, only=["_secret_id"])
{'_secret_id': 1}
>>> user.fromdict({'_secret_id': 2}, exclude_underscore=False)
>>> dict(user, only=["_secret_id"])
{'_secret_id': 2}
Updating primary key:
>>> user = session.query(User).first()
>>> dict(user, only=["id"])
{'id': 3}
>>> user.fromdict({'id': 2}, allow_pk=True)
>>> dict(user, only=["id"])
{'id': 2}
Updating relationships:
>>> dict(user, follow=['address'])
{'name': 'Gerald the Great', 'address': {'street': None}}
>>> user.fromdict({'address': {'street': 'Main street'})
>>> dict(user, follow=['address'])
{'name': 'Gerald the Great', 'address': {'street': 'Main street'}}
Using include:
>>> user = session.query(User).first()
>>> dict(user)
{'id': 3, 'name': 'Gerald', 'a_synonym': 'Data'}
>>> user.fromdict({'name': 'Gerald the Great', 'a_synonym': 'Other data'}, include=['a_synonym'])
>>> dict(user)
{'name': 'Gerald the Great', 'a_synonym': 'Other data'}
Using only:
>>> user = session.query(User).first()
>>> dict(user)
{'id': 3, 'name': 'Gerald', 'a_synonym': 'Data'}
>>> user.fromdict({'name': 'Gerald the Great', 'a_synonym': 'Other data'}, only=['name'])
>>> dict(user)
{'name': 'Gerald the Great', 'a_synonym': 'Data'}
Contains DictableModel that can be used as a base class for sqlalchemy.ext.declarative_base().
Bases: object
Can be used as a base class for sqlalchemy.ext.declarative()
Contains the methods DictableModel.__iter__(), DictableModel.asdict() and DictableModel.fromdict().
Variables: |
|
---|
iter method for models
Yields everything returned by asdict.
list of weak references to the object (if defined)
Get a dict from a model
Using the method parameter makes it possible to have multiple methods that formats the result.
Additional keyword arguments will be passed to all relationships that are followed. This can be used to pass on things like request or context.
Parameters: |
|
---|---|
Raises: | dictalchemy.errors.MissingRelationError if follow contains a non-existent relationship. |
Raises: | dictalchemy.errors.UnsupportedRelationError If follow contains an existing relationship that currently isn’t supported. |
Returns: | dict |
Update a model from a dict
Works almost identically as dictalchemy.utils.asdict(). However, it will not create missing instances or update collections.
This method updates the following properties on a model:
Parameters: |
|
---|---|
Raises: | dictalchemy.errors.DictalchemyError If a primary key is in data and allow_pk is False |
Returns: | The model |
Convert an argument that can be None, list/tuple or dict to dict
Example:
>>> arg_to_dict(None)
[]
>>> arg_to_dict(['a', 'b'])
{'a':{},'b':{}}
>>> arg_to_dict({'a':{'only': 'id'}, 'b':{'only': 'id'}})
{'a':{'only':'id'},'b':{'only':'id'}}
Returns: | dict with keys and dict arguments as value |
---|
Get a dict from a model
Using the method parameter makes it possible to have multiple methods that formats the result.
Additional keyword arguments will be passed to all relationships that are followed. This can be used to pass on things like request or context.
Parameters: |
|
---|---|
Raises: | dictalchemy.errors.MissingRelationError if follow contains a non-existent relationship. |
Raises: | dictalchemy.errors.UnsupportedRelationError If follow contains an existing relationship that currently isn’t supported. |
Returns: | dict |
Update a model from a dict
Works almost identically as dictalchemy.utils.asdict(). However, it will not create missing instances or update collections.
This method updates the following properties on a model:
Parameters: |
|
---|---|
Raises: | dictalchemy.errors.DictalchemyError If a primary key is in data and allow_pk is False |
Returns: | The model |
Make a class dictable
Useful for when the Base class is already defined, for example when using Flask-SQLAlchemy.
Warning: This method will overwrite existing attributes if they exists.
Parameters: |
|
---|---|
Returns: | The class |
Bases: exceptions.Exception
Base class for Dictalchemy errors
Bases: dictalchemy.errors.DictalchemyError
Raised when a relationship is missing
Variables: | relation_key – Relation name |
---|
Bases: dictalchemy.errors.DictalchemyError
Raised when a relation is not supported by asdict or fromdict.
Variables: | relation_key – Relation name |
---|
Dictalchemy supports python 2.7.3 and python 3.3 through 2to3. Other versions are not tested.
The source is hosted on http://github.com/danielholmstrom/dictalchemy.