gpt4 book ai didi

python - SQLAlchemy 加入复合外键(使用 flask-sqlalchemy)

转载 作者:太空狗 更新时间:2023-10-29 21:46:15 24 4
gpt4 key购买 nike

我试图了解如何在 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.:在我的实际应用程序代码中,问题实际上有点复杂,因为这些表在不同的模式上,我将使用绑定(bind):

app.config['SQLALCHEMY_BINDS'] = {
'assets': 'mysql+mysqldb://fooserver/assets',
'zabumbas': 'mysql+mysqldb://fooserver/zabumbas',
}

然后我将在表上声明不同的绑定(bind)。那我应该如何声明ForeignKeyConstraint呢?

最佳答案

您的代码有几个拼写错误,更正这些错误将使整个代码正常工作。

正确定义ForeignKeyConstraint:

  • 不是只定义它,你必须将它添加到__table_args__
  • columnsrefcolumns 参数的定义是相反的(参见 documentation)
  • 列的名称必须是数据库中的名称,而不是ORM属性的名称

如下代码所示:

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)

关于python - SQLAlchemy 加入复合外键(使用 flask-sqlalchemy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com