From 861f98aa29672c5badb062f81469ef1b3414cc62 Mon Sep 17 00:00:00 2001 From: Konsta Vesterinen Date: Thu, 30 Jan 2014 13:02:14 +0200 Subject: [PATCH] Add force_auto_coercion --- docs/coercion.rst | 32 ++-------------------------- sqlalchemy_utils/listeners.py | 40 ++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 31 deletions(-) diff --git a/docs/coercion.rst b/docs/coercion.rst index 16c136d..102faaa 100644 --- a/docs/coercion.rst +++ b/docs/coercion.rst @@ -4,35 +4,7 @@ Using automatic data coercion SQLAlchemy-Utils provides various new data types for SQLAlchemy and in order to gain full advantage of these datatypes you should use coercion_listener. Setting up the listener is easy: -:: - import sqlalchemy as sa - from sqlalchemy_utils import coercion_listener +.. module:: sqlalchemy_utils.listeners - - sa.event.listen(sa.orm.mapper, 'mapper_configured', coercion_listener) - - -The listener automatically detects SQLAlchemy-Utils compatible data types and coerces all attributes -using these types to appropriate objects. - - -Example -:: - - - from colour import Color - from sqlalchemy_utils import ColorType - - - class Document(Base): - __tablename__ = 'document' - id = sa.Column(sa.Integer, autoincrement=True) - name = sa.Column(sa.Unicode(50)) - background_color = sa.Column(ColorType) - - - document = Document() - document.background_color = 'F5F5F5' - document.background_color # Color object - session.commit() +.. autofunction:: force_auto_coercion diff --git a/sqlalchemy_utils/listeners.py b/sqlalchemy_utils/listeners.py index 9783183..10c21d0 100644 --- a/sqlalchemy_utils/listeners.py +++ b/sqlalchemy_utils/listeners.py @@ -28,7 +28,45 @@ def instant_defaults_listener(target, args, kwargs): setattr(target, key, column.default.arg) -def coerce_data_types(mapper=sa.orm.mapper): +def force_auto_coercion(mapper=sa.orm.mapper): + """ + Function that assigns automatic data type coercion for all classes which + are of type of given mapper. The coercion is applied to all coercion + capable properties. By default coercion is applied to all SQLAlchemy + mappers. + + Before initializing your models you need to call force_auto_coercion. + + :: + + from sqlalchemy_utils import force_auto_coercion + + + force_auto_coercion() + + + Then define your models the usual way:: + + + class Document(Base): + __tablename__ = 'document' + id = sa.Column(sa.Integer, autoincrement=True) + name = sa.Column(sa.Unicode(50)) + background_color = sa.Column(ColorType) + + + Now scalar values for coercion capable data types will convert to + appropriate value objects:: + + document = Document() + document.background_color = 'F5F5F5' + document.background_color # Color object + session.commit() + + + :param mapper: The mapper which the automatic data type coercion should be + applied to + """ sa.event.listen(mapper, 'mapper_configured', coercion_listener)