This library adds basic functionality for getting a dict from an SQLAlchemy model and updating a model from a dict.
SQLAlchemy is a very complex library. It contains synonyms, lists, sets, mixins and god knows what. Automatically convert that to a dict or update from a dict is not a simple task. This library should not be used on more complex models without thorough testing, it should however be fine to use on simple models.
There are two ways to use dictalchemy. Either by using dictalchemy.classes.DictableModel as base class or by using dictalchemy.utils.make_class_dictable() on an existing base class.
The actual work is done in the functions dictalchemy.utils.asdict() and dictalchemy.utils.fromdict().
Since attributes are checked on instances each instance can get their own setup of rules. This can be useful when returning a model instance as a response. If default values are set on that specific instance calling dict will render it properly.
Use dictalchemy.classes.DictableModel as a base class for sqlalchemy.ext.declarative_base.
Example:
from sqlalchemy.ext import declarative_base
from dictalchemy import DictableModel
Base = declarative_base(cls=DictableModel)
dictalchemy.utils.make_class_dictable() adds methods and attributes to an already existing class
Example:
from sqlalchemy.ext import declarative_base
from dictalchemy import make_class_dictable
base = declarative_base()
make_class_dictable(base)
Dictalchemy uses some basic attributes and parameters to convert to and from dict. The most basic are:
The defaults varies depending on the flag. For example, allow_pk will by default be set to True for fromdict and exclude_pk will be set to False in asdict.
A class or model can have these attributes set, prefixed with dictalchemy_. Some of them can also be overridden depending on if dictalchemy.utils.asdict() or dictalchemy.utils.fromdict() is called. If they are set they will override the more basic attribute.
Synonyms wraps a reader and a writer method. These methods can do whatever they want to so there is no way to safely updated data with synonyms. So keep in mind that using synonyms will make it possible to circumvent for example dictalchemy_exclude_pk.
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().
Example usage:
>>> from dictalchemy import DictableModel
>>> from slqlachemy.ext.declarative import declarative_base
>>> Base = declarative_base(cls=DictableModel)
Variables: |
|
---|
Get a dict from a model
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 include(for example for including synonyms/properties):
session.query(User).asdict(include=['displayname']
{'id': 1, 'username': 'Gerald', 'displayname': 'Gerald'}
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.DictalchemyError If a primary key is in data and allow_pk is False |
Returns: | The model |
Get a dict from a model
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 include(for example for including synonyms/properties):
session.query(User).asdict(include=['displayname']
{'id': 1, 'username': 'Gerald', 'displayname': 'Gerald'}
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.DictalchemyError If a primary key is in data and allow_pk is False |
Returns: | The model |
Get column keys for a model
Returns: | List of column keys |
---|
Get the column properties that affects a primary key
Returns: | Set of column keys |
---|
Get relation keys for a model
Returns: | List of RelationProperties |
---|
Get synonym keys for a model
Returns: | List of keys for synonyms |
---|
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
The name of the relation can be accessed from ‘relation_key’
Bases: dictalchemy.errors.DictalchemyError
Raised when a relation is not supported by asdict or fromdict.
The name of the relation can be accessed from ‘relation_key’