简体   繁体   English

Flask-SQLAlchemy连接是否可以从一个表中选择所有列,并从另一个表中指定一些列?

[英]Is it possible with Flask-SQLAlchemy join to select all columns from one table and specify some from another?

I'm doing a join of two tables and want to select all the columns from one and only some from another. 我正在连接两个表,并希望从一个表中选择所有列,而从另一个表中选择一些列。 I feel like I'm close, but it's not quite returning what I want. 我感觉自己已经接近了,但是还不能完全返回我想要的东西。 I have an advertisement table and a coupon table in where they have a 1 to 1 relationship. 我有一个广告表和一张优惠券表,它们之间存在1对1的关系。

I have called a query on the db model like so: 我在数据库模型上调用了查询,如下所示:

result = Advertisement.query.join(Coupon, 
Advertisement.id==Coupon.id).filter(Advertisement.date==Coupon.date, 
Advertisement.id==12345).add_columns(Coupon.discount, 
Coupon.expiry_date)

What I want to get back is all the columns from Advertisement and the two from Coupon. 我想找回的是Advertisement的所有列和Coupon的两列。 My understanding was that add_columns would do this, but I only get back the two from Coupon and nothing from Advertisement. 我的理解是add_columns可以做到这一点,但是我只能从Coupon中取回两个,而从Advertisement中什么也不能取。 While if I remove add_columns I get back all from Advertisement but nothing from Coupon. 当我删除add_columns时,我会从Advertisement中取回所有内容,而从Coupon中得不到任何内容。

Do I have to declare the table relationship in the class? 我必须在类中声明表关系吗? I know what the query should look like in sql, but I'm at a bit of a loss here. 我知道查询在sql中应该是什么样子,但是我有点茫然。 If the information I gave isn't clear enough, let me know and I can try to elaborate further, thanks. 如果我提供的信息不够清楚,请告诉我,我可以尝试进一步阐述,谢谢。

You can do it as follows: 您可以按照以下步骤进行操作:

result = session.query(Advertisement, Coupon.discount, Coupon.expiry_date).filter(
   Advertisement.id==Coupon.id, 
   Advertisement.date==Coupon.date, 
   Advertisement.id==12345
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM