我正在尝试了解如何在SQLAlchemy上使用复合外键进行连接,而我尝试这样做的尝试失败了。
我的玩具模型上有以下模型类(我使用的是Flask-SQLAlchemy,但我不确定这与问题有什么关系):
# coding=utf-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class Asset(db.Model):
__tablename__ = 'asset'
user = db.Column('usuario', db.Integer, primary_key=True)
profile = db.Column('perfil', db.Integer, primary_key=True)
name = db.Column('nome', db.Unicode(255))
def __str__(self):
return u"Asset({}, {}, {})".format(self.user, self.profile, self.name).encode('utf-8')
class Zabumba(db.Model):
__tablename__ = 'zabumba'
db.ForeignKeyConstraint(
['asset.user', 'asset.profile'],
['zabumba.user', 'zabumba.profile']
)
user = db.Column('usuario', db.Integer, primary_key=True)
profile = db.Column('perfil', db.Integer, primary_key=True)
count = db.Column('qtdade', db.Integer)
def __str__(self):
return u"Zabumba({}, {}, {})".format(self.user, self.profile, self.count).encode('utf-8')
然后我用一些假数据填充数据库:
db.drop_all()
db.create_all()
db.session.add(Asset(user=1, profile=1, name=u"Pafúncio"))
db.session.add(Asset(user=1, profile=2, name=u"Skavurska"))
db.session.add(Asset(user=2, profile=1, name=u"Ermengarda"))
db.session.add(Zabumba(user=1, profile=1, count=10))
db.session.add(Zabumba(user=1, profile=2, count=11))
db.session.add(Zabumba(user=2, profile=1, count=12))
db.session.commit()
并尝试了以下查询:
> for asset, zabumba in db.session.query(Zabumba).join(Asset).all():
> print "{:25}\t<---->\t{:25}".format(asset, zabumba)
但SQLAlchemy告诉我,它无法为此连接找到足够的外键:
Traceback (most recent call last):
File "sqlalchemy_join.py", line 65, in <module>
for asset, zabumba in db.session.query(Zabumba).join(Asset).all():
File "/home/calsaverini/.virtualenvs/recsys/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1724, in join
from_joinpoint=from_joinpoint)
File "<string>", line 2, in _join
File "/home/calsaverini/.virtualenvs/recsys/local/lib/python2.7/site-packages/sqlalchemy/orm/base.py", line 191, in generate
fn(self, *args[1:], **kw)
File "/home/calsaverini/.virtualenvs/recsys/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1858, in _join
outerjoin, create_aliases, prop)
File "/home/calsaverini/.virtualenvs/recsys/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1928, in _join_left_to_right
self._join_to_left(l_info, left, right, onclause, outerjoin)
File "/home/calsaverini/.virtualenvs/recsys/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2056, in _join_to_left
"Tried joining to %s, but got: %s" % (right, ae))
sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from. Tried joining to <class '__main__.Asset'>, but got: Can't find any foreign key relationships between 'zabumba' and 'asset'.
我尝试了很多其他方法:在两个表上声明ForeignKeyConstraint
或将查询反转为db.session.query(Asset).join(Zabumba).all()
。
我做错了什么?
感谢。
P.S。:在我的实际应用程序代码中,问题实际上有点复杂,因为这些表在不同的模式上,我将使用绑定的东西:
app.config['SQLALCHEMY_BINDS'] = {
'assets': 'mysql+mysqldb://fooserver/assets',
'zabumbas': 'mysql+mysqldb://fooserver/zabumbas',
}
然后我将声明表格上的不同绑定。我应该如何声明ForeignKeyConstraint
呢?
答案 0 :(得分:6)
你的代码中只有很少的拼写错误,纠正这将使整个代码工作。
正确定义ForeignKeyConstraint
:
__table_args__
如下面的代码所示:
class Zabumba(db.Model):
__tablename__ = 'zabumba'
__table_args__ = (
db.ForeignKeyConstraint(
['usuario', 'perfil'],
['asset.usuario', 'asset.perfil'],
),
)
通过在查询子句中包含两个类来正确构造查询:
for asset, zabumba in db.session.query(Asset, Zabumba).join(Zabumba).all():
print "{:25}\t<---->\t{:25}".format(asset, zabumba)