我从事Postgres的工作,并从SQL Alchemy开始。我创建了“ layout_api.py”
layout_api.py
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:password@10.***.**.**/gridcustomization"
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)
user_id = Column(UUID(as_uuid=True), nullable=False)
ispublic = Column(Integer, default=0, nullable=False)
isactive = Column(Integer, default=0, nullable=False)
createdby = Column(Integer, default=1, nullable=False)
现在我只需要特定的列。 与在SQL中一样,我们编写:
SELECT layout_id, user_id, isactive FROM col.layout;
我在SQL Alchemy中尝试了相同的方法,但是没有得到输出。
fetch_columns_data.py
class DBFetch:
def get(self):
Session = sessionmaker(bind=db) #make session to query data
session = Session()
Base.metadata.create_all(db)
session.query("SET search_path TO col")
result = []
selected_columns = Layout.__table__.columns # specific columns selected by user
print("Selected columns {}".format(selected_columns))
record = session.query(Layout).with_entities(*selected_columns).one()
for row in record:
result.append((row._asdict()))
print(result)
如何从数据库中获取特定的列数据?我正在为仅需要特定列数据的用户尝试此操作。给我建议。预先感谢。