繁体   English   中英

根据另一个表fastAPI和sqlalchemy的Id从表中取数据

[英]Fetching data from the table based on the Id of another table fastAPI and sqlalchemy

我想做一个数据库操作,我有 2 个表(Table1 和 Table2)。 表 1 中有一个“id”列,表 2 中有 4 列(id、服务器、端口、端点)。 所以我想比较两个表的 id,如果匹配,我想要服务器、端口和端点的详细信息。 我正在使用带有 sqlalchemy 的 fastAPI。

Model 文件是这样的

#Table1
class ResponseDetails(Base):
    __tablename__ = "response"
    id = Column(String, unique=True, index=True, nullable=False)
#Table2
class AlgoDetails(Base):
    __tablename__ = "algo_details"
    id = Column(String, unique=True, index=True, nullable=False)
    server = Column(String(100), index=True, nullable=False)
    port = Column(String, index=True, nullable=False)
    endpoint = Column(String, index=True, nullable=False)

现在我想要两个表的 id,如果匹配,我想从表 2 中打印服务器、端口和端点。我也不想编写原始 sql 查询。 我想写一个基于 ORM 的查询。

例如

result = db.query(response_model.ResponseDetails).offset(skip).limit(limit).all()
#The basically give each and every rows exist in a particular table.
or
db.query(response_model.ResponseDetails).filter(response_model.ResponseDetails.id == job_id).first()
#The basically give data corresponds to the given input id

我的数据库连接文件


from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./database.db"
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

谢谢。

我对您的代码进行了一些修改,因为几行在 id 列定义和 table1 name("response") 处给了我一个错误

class Table1(Base):
    __tablename__ = "table1"
    id = Column(String, primary_key=True, index=True)
    
class Table2(Base):
    __tablename__ = "table2"
    id = Column(String, primary_key=True, index=True)
    server = Column(String(100), index=True, nullable=False)
    port = Column(String, index=True, nullable=False)
    endpoint = Column(String, index=True, nullable=False)

# Insert few rows in tables
db.add(Table1(id=1))
db.add(Table1(id=2))
db.add(Table1(id=3))

db.add(Table2(id=1, server='localhost', port=8000, endpoint='/home'))
db.add(Table2(id=2, server='localhost', port=8000, endpoint='/cart'))
db.add(Table2(id=5, server='localhost', port=8000, endpoint='/item'))

db.commit()

现在当我执行这个查询时:

result = db.query(Table2).filter(Table1.id == Table2.id).all()
for row in result:
    print(row.server, row.port, row.endpoint)

我从 table2 中获得了 id 等于表 1 中的 id 的行

localhost 8000 /home
localhost 8000 /cart

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM