如何从两个表中使用flask-sqlalchemy查询连接返回所有列 [英] How to return all the columns with flask-sqlalchemy query join from two tables

查看:23
本文介绍了如何从两个表中使用flask-sqlalchemy查询连接返回所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从flask-sqlalchemy中的两个表进行连接,我想要两个表中的所有列,但如果我执行:

I'm trying to do a join from two tables in flask-sqlalchemy and I want all the columns from both tables but if I execute:

Company.query.join(Buyer, Buyer.buyer_id == Company.id).all()

我只有来自 Company 的列(它返回,实际上是一个 Company 对象).

I have only the columns from Company (It returns, in fact, a Company object).

我知道我可以这样做:

Company.query.join(Buyer, Buyer.buyer_id == Company.id) \
             .add_columns(Buyer.id, Buyer.name, etc..).all()

在这种情况下返回:

(<Company 2>, 1, 'S67FG', etc..)

问题是我有很多列,而且我不知道如何使用flask-marshmallow(嵌套字段不起作用)来处理返回的obj.

the problem is that I have a lot of columns and also I don't know how to marshmallow the returned obj with flask-marshmallow (with nested fields does not work).

有没有办法用两个表中的列返回一个新的obj?对您而言,管理这些情况的最佳方法是什么?

Is there a way to return a new obj with columns from the two tables? What is for you the best way to manage these situations?

非常感谢任何建议.谢谢

Any suggestion is highly appreciated. Thanks

推荐答案

最后我通过使用这个简单的 sqlalchemy 查询实现了这一点:

at the end I've achieved this by using this simple sqlalchemy query:

db.session.query(Company, Buyer).join(Buyer, Buyer.buyer_id == Company.id).all()

它返回:

(<Company 2>, <Buyer 1, 2>)

这篇关于如何从两个表中使用flask-sqlalchemy查询连接返回所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆