【问题标题】:SQLAlchemy ORM autoloading with relationshipsSQLAlchemy ORM 自动加载关系
【发布时间】:2020-12-14 11:20:54
【问题描述】:

我从一项服务(不使用 sqlalchemy)创建了一个表,现在我想使用 sqlalchemy 查询表

我使用了这样的语法

from app import db, engine, Base
from sqlalchemy import Table, Column, String, Integer, TIMESTAMP, Float


class Post(Base):
    __table__ = Table('posts', Base.metadata,
                      autoload=True, autoload_with=engine)
    

这是有效的,我可以查询我的对象。

令人烦恼的是,我无法在运行前获取属性,因为(显然)在它编译之前什么都没有。有没有办法在使用这样的东西时添加类型,还是我必须假设它们在那里?

【问题讨论】:

  • 好吧,您可以根据您对表结构的了解,在您的类中硬编码适当的Column 对象,但是只是以您现在的方式反映它们有什么问题,然后只是“假设[列]在那里”?
  • 顺便说一句,autoload=True 已过时;只需使用autoload_with=engine
  • @GordThompson 感谢您的提示!我想这不是问题。但是关系呢?

标签: python flask sqlalchemy flask-sqlalchemy


【解决方案1】:

对于现有表,我们可以反映特定于表的信息(列、FK 等),并且仍然添加我们自己的额外 ORM 特定属性,例如关系:

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

print(sa.__version__)  # 1.3.20
connection_uri = "mssql+pyodbc://@mssqlLocal64"
engine = sa.create_engine(connection_uri, echo=False)

# show existing sample data
with engine.connect() as conn:
    results = conn.execute(sa.text("SELECT * FROM users"))
    print([dict(r) for r in results])
    # [{'id': 1, 'name': 'Gord'}]
    results = conn.execute(sa.text("SELECT * FROM posts"))
    print([dict(r) for r in results])
    # [{'id': 1, 'user_id': 1, 'post': 'Hello world!'}]

Base = declarative_base()
meta = Base.metadata


class User(Base):
    __table__ = sa.Table("users", meta, autoload_with=engine)


class Post(Base):
    __table__ = sa.Table("posts", meta, autoload_with=engine)
    author = sa.orm.relationship("User")

    def __repr__(self):
        return f"<Post(id={self.id}, author_name='{self.author.name}', post='{self.post}')>"


Session = sessionmaker(bind=engine)
session = Session()

my_post = session.query(Post).get(1)
print(my_post)  # <Post(id=1, author_name='Gord', post='Hello world!')>

【讨论】:

  • 在性能方面我只有三个关系。很公平,我刚刚手动过滤了author = .... book = session.query(Book).filter(author_id = author.id) ,就以您演示的方式实现它而言,这是一种不好的做法吗?
猜你喜欢
  • 2014-10-13
  • 2012-07-31
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 2021-09-18
相关资源
最近更新 更多