[英]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.