Thanks for the code. For those who might also be interested in an ORM base
class providing __init__, update and __repr__ - this is what I use now with
0.5 (comments welcome):

=================================================
import sqlalchemy as sql
from sqlalchemy import orm

class MyOrm(object):
    def __init__(self, **kw):
        """Create a mapped object with preset attributes"""
        for key, value in kw.iteritems():
            if hasattr(self, key):
                setattr(self, key, value)
            elif not ignore_missing_columns:
                raise AttributeError('Cannot set attribute which is not column 
in mapped table: %s' % (key,))

    def update(self, update_dict, ignore_missing_columns=True):
        """Update an object's attributes from a dictionary"""
        for key, value in update_dict.iteritems():
            if hasattr(self, key):
                setattr(self, key, value)
            elif not ignore_missing_columns:
                raise AttributeError('Cannot set attribute which is not column 
in mapped table: %s' % (key,))

    def __repr__(self):
        """Return a decent printable representation of a mapped object and
        its attributes."""
        atts = []
        columns = orm.object_mapper(self).mapped_table.c
        for column in columns:
            key = column.key
            if hasattr(self, key):
                col = columns.get(key)
                if not (getattr(col, 'server_default', None) is not None or
                        isinstance(getattr(col, 'default', None), 
sql.PassiveDefault) or
                        getattr(self, key) is None):
                    atts.append( (key, getattr(self, key)) )
        return self.__class__.__name__ + '(' + ', '.join(x[0] + '=' + 
repr(x[1]) for x in atts) + ')'
=================================================

Would be nice if mapped objects could automatically get such methods
assigned. Not sure if SQLAlchemy can or should provide that or if it
broke other functionality.

Cheers
 Christoph

Attachment: signature.asc
Description: This is a digitally signed message part.

Reply via email to