[Python] SQLAlchemy - Passing a list of Column to Table constructor

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I predefine a list of Column objects that I want to pass to the Table constructor

    from sqlalchemy import create_engine as sqla_create_engine
    from sqlalchemy import Table as sqla_Table
    from sqlalchemy import Column as sqla_Column
    from sqlalchemy import Integer as sqla_Integer
    from sqlalchemy import String as sqla_String
    from sqlalchemy import MetaData as sqla_MetaData


    myColsX = [sqla_Column("id", sqla_Integer, primary_key=True),
    sqla_Column('namex', sqla_String(15)),
    sqla_Column('comment', sqla_String(120))]


    If I call the Table constructor, with each Column instance, -- no problem:

    myTable = sqla_Table(myTableNameX, myMetaData,
    sqla_Column("id", sqla_Integer, primary_key=True),
    sqla_Column('namex', sqla_String(15)),
    sqla_Column('comment', sqla_String(120)),
    extend_existing=True)
    myMetaData.create_all(myEngine, tables=[myTable], checkfirst=True)


    ...and I can call the Table construct multiple times with interleaving DROP table calls.

    If on the other hand I pass the list of Column as:

    myTable = sqla_Table(myTableNameX, myMetaData, *myColsX,
    extend_existing=True)


    The Table is created the first time, but with a subsequent call following a DROP command

    I get an error

    sqlalchemy.exc.ArgumentError: Column object 'id' already assigned to Table 'tableX


    Note also that I have tried various combinations of the Table flags: eg autoload=True, extend_existing=True, etc.

    What is the correct way to create and pass the list of Column to the Table constructor?

    Thanks.

    Continue reading...

Compartilhe esta Página