【问题标题】:No data fetched for query(table_class).all() - sqlalchemy ORM没有为查询(table_class).all()获取数据 - sqlalchemy ORM
【发布时间】:2021-02-06 07:19:47
【问题描述】:

我正在尝试简单地执行“从表中选择 *”,但它返回一个空列表。

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)
);

可能的问题是什么?

【问题讨论】:

    标签: orm sqlalchemy


    【解决方案1】:

    您应该使用__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)
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2017-11-28
      • 2019-04-07
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多