我是Postgresql和Sqlalchemy的新手。我有下面的文件layout.py。在此,我在“ col”模式下创建了两个表名“ layout”和“ layout default”。
import json, decimal
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer, TIMESTAMP, Sequence, text, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime, uuid
db_string = "postgres://postgres:PWDd@10.**.**.***:1111/d_demo"
Base = declarative_base()
db = create_engine(db_string)
class Layout(Base):
__tablename__ = "col.layout"
layout_id = Column(UUID(as_uuid=True), nullable=False, primary_key=True)
name = Column(String(1000), nullable=False)
layout = Column(String(10000), nullable=False)
grid_id = Column(Integer, nullable=False)
user_id = Column(Integer, nullable=False)
issystemlayout = Column(Integer, default=0, nullable=False)
ispublic = Column(Integer, default=0, nullable=False)
isactive = Column(Integer, default=0, nullable=False)
createdby = Column(Integer, default=1, nullable=False)
createdat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedby = Column(Integer, default=1, nullable=False)
插入数据:
INSERT INTO col.layout(layout_id,name,layout,grid_id,user_id,ispublic,issystemlayout,isactive,createdby,createdat, modifiedat,modifiedby) VALUES('ba0233d7-d917-4303-b4bf-c2544a617d33','Layout1','{"Name":"Manish","Place":"Pune"}',1,12345,'1','0','1','201819','2015/05/20','2015/05/16',123);
获取数据:
Session = sessionmaker(bind=db)
session = Session()
Base.metadata.create_all(db)
session.query("SET search_path TO col;")
result = []
selected_columns = Layout.__table__.columns
print("Selected columns {}".format(selected_columns))
record = session.query(Layout).with_entities(*selected_columns).all()
for row in record:
print(row)
result.append(row)
print(json.dumps(result))
session.close()
但是它没有显示“ col”模式下的数据。请提出建议,我该怎么办?
答案 0 :(得分:1)
https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html#table-configuration
Postgres数据库的架构可以通过 table_args 属性作为元组或dict传递。
因此,对于您的问题,您的类定义应具有以下额外属性:
class Layout(Base):
__tablename__ = "layout"
__table_args__ = {"schema": "col"}
layout_id = Column(UUID(as_uuid=True), nullable=False, primary_key=True)
name = Column(String(1000), nullable=False)
layout = Column(String(10000), nullable=False)
grid_id = Column(Integer, nullable=False)
user_id = Column(Integer, nullable=False)
issystemlayout = Column(Integer, default=0, nullable=False)
ispublic = Column(Integer, default=0, nullable=False)
isactive = Column(Integer, default=0, nullable=False)
createdby = Column(Integer, default=1, nullable=False)
createdat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedby = Column(Integer, default=1, nullable=False)