for validation/mutation of incoming data you'd normally use the @validates 
decorator or set up a listener event:

http://www.sqlalchemy.org/docs/orm/mapper_config.html#simple-validators
http://www.sqlalchemy.org/docs/orm/events.html#sqlalchemy.orm.events.AttributeEvents

to mutate returned data on the "read" side, you need to wrap around the mapped 
attribute.     The most flexible way to do this is with the hybrid system, 
since it gives you control over the data side and the query side, and 
optionally lets you modify the write side as well not unlike how the validators 
work, except using plain descriptors:

from sqlalchemy.ext.hybrid import hybrid_property

class MyClass(Base):
    # ...

    _name = Column('name', String)
   
    @hybrid_property
    def name(self):
        return "my name is:" + self._name

Hybrids are introduced at 
http://www.sqlalchemy.org/docs/orm/extensions/hybrid.html .

if you don't like typing "name" so much it can be automated using a recipe I 
just made up at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/QuickHybrid , 
it would look like this:

class MyClass(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True)

    @mapped_column(String)
    def _name(self, value):
        return "The name is: " + value

the recipe maintains all the same capabilities as a hybrid with a separate 
column, just uses some mild trickery to combine the two steps.

On Oct 11, 2011, at 4:47 PM, Nathan Rice wrote:

> I need to add some processing to mapped attributes.  For instance,
> some extra client side validation, returning attribute values embedded
> in markup, etc.
> 
> Is there a better way to do this than to change the column definition
> (i.e. Column(name, type_, key="_name")) and adding a descriptor to the
> class' name attribute which then writes to _name?
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to