canni canni - 4 months ago 51
Python Question

How to set common prefix for all tables in SQLAlchemy

I know there is a way to instrument SQLAlchemy to prepend common

prefix
to all columns, is it possible to add a common
prefix
to all table names derived from single
declarative_base
?

Answer

Use declared_attr and a customized Base along the lines of:

from sqlalchemy.ext.declarative import declared_attr

class PrefixerBase(Base):

    __abstract__ = True

    _the_prefix = 'someprefix_'

    @declared_attr
    def __tablename__(cls):
        return cls._the_prefix + cls.__incomplete_tablename__


class SomeModel(PrefixerBase):

    __incomplete_tablename__ = 'sometable'
    ...

A class marked with __abstract__ will not get a table or mapper created and can act as the extended declarative base.

You could also make it even more implicit using a custom metaclass (originally described here):

from sqlalchemy.ext.declarative.api import DeclarativeMeta


class PrefixerMeta(DeclarativeMeta):

    def __init__(cls, name, bases, dict_):
        if '__tablename__' in dict_:
            cls.__tablename__ = dict_['__tablename__'] = \
                'someprefix_' + dict_['__tablename__']

        return super().__init__(name, bases, dict_)

Base = declarative_base(metaclass=PrefixerMeta)


class SomeModel(Base):

    __tablename__ = 'sometable'
    ...