Dynamically add attributes to existing SQL class and existing column

Viewed 29

Say I have a super simple class like:

Base = declarative_base()
class Parent(Base):
    __tablename__ = 'parent'
    id = Column('id', Integer, primary_key = True)
    name = Column('name', String)

The table "parent" has other columns (say for example date of birth) but I don't generally need them, so I would rather not map them. Let's say I'm writing a query where I do need one of these unmapped columns. Is there a way to map the column WITHOUT changing the Parent class? I want something like this:

setattr(Parent, 'DOB', Column("dateOfBirth", Date))

Is there an easy way to do this? Ideally I would be able to do this from a listof tuples with column and attribute names (eg [("DOB", 'dateOfBirth')])

The goal is to be able to access the data and also filter based on that column.

0 Answers
Related