V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
holinhot
V2EX  ›  Python

请教个 Python sqlalchemy join 问题

  •  
  •   holinhot · 2019-07-06 05:40:18 +08:00 · 2081 次点击
    这是一个创建于 1749 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想要按用户取出产品的价格
    原 SQL 工作语句
    select pro.id as id,
    pro.name as name,
    pri.year1 as year1
    from prices pri right outer join products pro on pri.product_id = pro.id where user_group_id=(select user_group_id from user_relationships where user_id=2);



    搞了一晚上了,还是没能成功转成 sqlalchemy 查询方法。
    products = Product.query.outerjoin(Price).filter_by(user_group_id=2)

    sqlalchemy 构建的句子是这样,没有返回价格信息,
    SELECT products.id AS products_id, products.name AS products_name, products.time_created AS products_time_created, products.time_updated AS products_time_updated
    FROM products LEFT OUTER JOIN prices ON products.id = prices.product_id
    WHERE prices.user_group_id = %s
    2 条回复    2019-07-07 16:54:42 +08:00
    dongyx
        1
    dongyx  
       2019-07-06 13:59:05 +08:00
    1.你的写法无法查出 Price 是因为你 query 的对象仅仅是 Product,尽管你做了显式 join,但是 SQLAlchemy 只会返回 Product 的信心。

    2. 正确的写法有很多种,具体要看你的 Product, Price, User 三个 model 类是怎样建立 SQLAlchemy relationships 的。

    其中一种最简单的写法,不管你三个类是什么关系都能用的写法,是隐式 jcross join: session.query(Product, Price).filter(Product.id == Price.id & Price.user_group_id == 2)
    holinhot
        2
    holinhot  
    OP
       2019-07-07 16:54:42 +08:00
    @dongyx 今天又搞了几小时弄好了
    用 model 开始的查询 只返回 model 表的数据。 改用 db.session.query 并设置了别名
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4180 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 10:12 · PVG 18:12 · LAX 03:12 · JFK 06:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.