首页 > 解决方案 > 没有为查询(table_class).all()获取数据 - sqlalchemy ORM

问题描述

我试图简单地做一个“从表中选择 *”,但它返回一个空列表。

import os

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, text

SQLALCHEMY_DATABASE_URL = "postgres+psycopg2://postgres:pwd@localhost:5432/postgres"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(engine)

Base = declarative_base()
    
class CPMyTable(Base):
    __tablename__ = 'cp.my_table'

    c_id = Column(Integer)
    c_s_id = Column(Integer, primary_key=True)
    c_s = Column(String)
    
db_session = SessionLocal()
Base.metadata.create_all(engine)

print(db_session.query(CPMyTable).all())

输出:

[]

我正在查询的表的 DDL 是:

CREATE TABLE cp.my_table (
    c_id int4 NULL,
    c_s_id serial NOT NULL,
    c_s text NULL,
    CONSTRAINT mytable_pk PRIMARY KEY (c_s_id)
);

可能的问题是什么?

标签: ormsqlalchemy

解决方案


您应该使用__table_args__来指定架构。

class CPMyTable(Base):
    __tablename__ = 'my_table'
    __table_args__ = {'schema': 'cp'}

    c_id = Column(Integer)
    c_s_id = Column(Integer, primary_key=True)
    c_s = Column(String)

推荐阅读