Class with automap should override all columns?

Issue #3838 closed
George Papadrosou created an issue

Hi,

I have this example:

def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
    print base, local_cls, referred_cls, constraint
    name = referred_cls.__name__.lower() + "_ref"
    return name

def exclude_tables(name, metadata):
    # these tables have no columns and SqlAlchemy reflect fails
    return name not in [
        'table1',
        'table2',
        'table3'
    ]

engine = create_engine('postgresql://...')
metadata = MetaData(bind=engine)
MyBase = automap_base(metadata=metadata)

class CarrierGroup(MyBase):
    __tablename__ = 'carrier_group'
    group_id = Column(Integer, Sequence('carrier_group_group_id_seq'), primary_key=True)
    # group_name = Column(String)  # commented but exists in DB

metadata.reflect(only=exclude_tables)
MyBase.prepare(name_for_scalar_relationship=name_for_scalar_relationship)

Session = scoped_session(sessionmaker())
session = Session()
session.add(CarrierGroup(group_name='testgroup'))

This code fails in the last statement with "TypeError: 'group_name' is an invalid keyword argument for CarrierGroup ". Why? If I want to create a Class, do I need to explicitly write all the fields?

Thank you

Comments (5)

  1. Mike Bayer repo owner

    Hello -

    because you are pre-declaring a Table and not using Base.prepare(), you need to pass additional options to metadata.reflect():

    metadata.reflect(extend_existing=True)
    

    This because reflection does not re-reflect an existing Table object unless this flag is passed.

    Base.prepare() already adds extend_existing=True when it invokes reflection for each Table.

    You also probably want to add autoload_replace=False:

    metadata.reflect(extend_existing=True, autoload_replace=False)
    

    this so that the Column objects you've placed in your pre-declared Table definitions aren't overridden by what's reflected. Base.prepare() also calls with this argument.

    Please note as per the bug reporting guidelines that this is a usage question and not a bug report, the mailing list should be used for these. thanks!

  2. Log in to comment