You could inject the attributes in a metaclass:

def common_columns():
    return dict(id = Column(Integer, primary_key=True),
                foo = Column(String))

Base = None

class mymeta(DeclarativeMeta):
    def __init__(self, name, bases, attrs):
        if Base is not None:
            # a real sub class
            attrs.update(common_columns())
        DeclarativeMeta.__init__(self, name, bases, attrs)

Base = declarative_base(metaclass=mymeta)

But note that the declarative system has a counter so the column
definitions are ordered correctly for create statements.  I don't know
if this would adversely affect that.

On Dec 17, 9:30 pm, Chris Withers <ch...@simplistix.co.uk> wrote:
> Hi All,
>
> So, say you have some common methods and field definitions that you want
> to share across a bunch of mapper classes. My python head says that
> these should all go in a base class, say, for example:
>
> from sqlalchemy.ext.declarative import declarative_base
> from sqlalchemy.schema import Column
> from sqlalchemy.types import  Integer, String, DateTime
>
> Base = declarative_base()
>
> class TheBase(Base):
>
>      id =  Column(Integer, primary_key=True)
>      ref = Column(Integer, nullable=False, index=True)
>      valid_from = Column(DateTime(), nullable=False, index=True)
>      valid_to = Column(DateTime(), index=True)
>      entered_by = Column(String(255), nullable=False, index=True)
>      deleted_by = Column(String(255), index=True)
>
>      def some_func(self, x,y):
>         ...
>
> But, this results in:
>
> sqlalchemy.exc.InvalidRequestError: Class <class 'TheBase'> does not
> have a __table__ or __tablename__ specified and does not inherit from an
> existing table-mapped class.
>
> How should I create a class like this? This isn't about table
> inheritance or the like and I'm *sure* I was told an easy solution for
> this specific use case before, but I can't find it for the life of me now...
>
> Chris
>
> --
> Simplistix - Content Management, Batch Processing & Python Consulting
>              -http://www.simplistix.co.uk

--

You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@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