SQLAlchemy查询外键

时间:2020-04-04 00:51:51

标签: python-3.x jinja2 flask-sqlalchemy

我有一个Sqlalchemy问题。如果我有一个数据库(sqlite)和三个表Buyers EventsEvent_details,如下例所示。 Event_details表具有Buyers主键和Events主键的外键。

如何编写一个查询,内容如下:

If  Buyers.id is in Event_details.buyers_id:
     show me the Events.eventname that matches the Event_details.event_id

这很令人困惑,但是我实际上是在试图理解外键的连接以及如何查询数据库中的外键。谢谢!

我目前拥有的是

events = db.session.query(Event_details).filter(Event_details.buyer_id == current_user.id)

但这只是返回匹配的event_details名称,而没有引用Event.eventname。谢谢! enter image description here

1 个答案:

答案 0 :(得分:0)

如果有人需要答案,我发现了另一篇有用的文章。

How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two?

我的查询是

events = db.session.query(Events).filter(Events.id == Eventdetails.events_id).filter(Eventdetails.buyer_id == Buyers.id).filter(Buyers.id == current_user.id)

基本上是说,让我了解所有活动 filter by the Events.id matching Eventdetails.event_id filter this by all Eventdetails.buyer.id that match Buyer.id Finally one match the Buyers.id of the currently logged in user.