sqlalchemy.exc.InvalidRequestError: Table 'thetab' is already defined for this MetaData instance

Viewed 26

In one of my GET call, I need to pass to the query function a declarative class for which the name is supposed to change dynamically:

async def get_computers_both(db: Session, table_name: str, q: str = "", skip: int = 0, limit: str = "100"):

    class Computer(Base):
        __tablename__ = table_name
        extend_existing = True
        id = Column(Integer, primary_key=True, index=True)


    limit = str(limit)
    return db.query(Computer).filter(
        or_(
            Computer.computername.contains(q),
        )
    ).limit(limit).all()

Problem: every time I do this GET call (i.e. I load the corresponding webpage), I get:

sqlalchemy.exc.InvalidRequestError: Table 'thetab' is already defined for this MetaData instance. Specify 'extend_existin
g=True' to redefine options and columns on an existing Table object.

I have tried adding "extend_existing=True" when I create the Table object in the GET call:

@app.get("/computers/{db_name}/{table_name}", response_class=HTMLResponse)
async def read_computers(request: Request, db: Session = Depends(get_custom_db)):

Where get_custom_db contains :

computers = sqlalchemy.Table(
    table_name,
    metadata,
    extend_existing=True,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("computername", sqlalchemy.String),
)

But still the same...

Many thanks!

0 Answers
Related