【问题标题】:Fetching data from the table based on the Id of another table fastAPI and sqlalchemy根据另一个表fastAPI和sqlalchemy的Id从表中获取数据
【发布时间】:2022-01-12 19:38:46
【问题描述】:

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

模型文件是这样的

#Table1
class RD(Base):
    __tablename__ = "table1"
    id = Column(String, unique=True, index=True, nullable=False)
#Table2
class AD(Base):
    __tablename__ = "table2"
    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 的查询。

我的数据库连接文件

谢谢。

【问题讨论】:

    标签: python database sqlite sqlalchemy fastapi


    【解决方案1】:

    我对您的代码进行了一些修改,因为有几行在 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
    

    【讨论】:

    • @PanicLoin 感谢您的回复。我尝试过这种方式,但 pydantic 向我抛出了这个“pydantic.error_wrappers.ValidationError:DetailsBase 的 5 个验证错误”,其中 DetailsBase 是一个类
    • 如果您在路径操作中使用 response_model,您能否显示您的架构文件
    • 完成了。谢谢
    • 太好了...如果它解决了您的问题,请接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多