尝试在 sqlalchemy orm 查询中加入两个表,出现错误
Posted
技术标签:
【中文标题】尝试在 sqlalchemy orm 查询中加入两个表,出现错误【英文标题】:Trying to join two tables in sqlalchemy orm query, getting an error 【发布时间】:2018-02-27 16:02:03 【问题描述】:尝试使用此命令连接下表:
Subscription.query.filter( return Subscription.query.filter(Subscription.watch_id == id).join(User).filter_by(watch_id=id)
我得到这个错误:
sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from. Tried joining to <class 'app.user.model.User'>, but got: Can't find any foreign key relationships between 'wm_subscription' and 'user'.
基本上我的最终目标是获取一个查询,该查询获取共享 watch_id 的用户列表。不确定模型或查询是否正确。有谁知道怎么回事?
Database = declarative_base(cls=DbBase)
class Subscription(Database):
__tablename__ = 'wm_subscription'
subscription_id = UniqueIdPk()
watch_id = UniqueIdRefNotNull(index=True)
user_id = UniqueIdRefNotNull(ForeignKey('User.user_id'), index=True)
subscription_watch = relationship('Watch',
primaryjoin='Subscription.watch_id == Watch.watch_id',
foreign_keys='Watch.watch_id',
uselist=True)
subscription_user = relationship('User',
primaryjoin='Subscription.watch_id == User.user_id',
foreign_keys='User.user_id',
uselist=True,
backref='user')
class User(Database, UserMixin):
__tablename__ = 'user'
user_id = UniqueIdPk()
# Google sub ID - unique to user https://developers.google.com/identity/protocols/OpenIDConnect
google_id = Column(String(length=50))
# override email mixin for unique index
email = Email(unique=True)
first_name = Name()
last_name = Name()
def get_id(self):
return self.user_id
【问题讨论】:
【参考方案1】:这是正确的查询:
Subscription.query.filter(Subscription.watch_id == id).join(User)
【讨论】:
以上是关于尝试在 sqlalchemy orm 查询中加入两个表,出现错误的主要内容,如果未能解决你的问题,请参考以下文章