Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to duplicate a table definition in SQLAlchemy?

I'm using declarative in SQLAlchemy and want to create a class that is identical to another columnwise, but be backed by a different table, e.g.:

Base = declarative_base()

class Foo(Base):
  __tablename__ = 'foo'
  id = Column(Integer, primary_key=True)
  a = Column(Text)
  b = Column(Text)

class Bar(Base):
  __tablename__ = 'bar'
  id = Column(Integer, primary_key=True)
  a = Column(Text)
  b = Column(Text)

In this example, I'd like to create the class Bar in such a way that any change to the column set of Foo is reflected in Bar. There is no relationship between this data so I don't think inheritance is the right way to go.

Does this make sense?

like image 914
EliteGreg Avatar asked Mar 18 '23 23:03

EliteGreg


1 Answers

Use a common mixin for both models:

class CommonModel(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True)
    a = Column(Text)
    b = Column(Text)


class Foo(CommonModel):
    __tablename__ = 'foo'


class Bar(CommonModel):
    __tablename__ = 'bar'
like image 69
davidism Avatar answered Apr 27 '23 00:04

davidism