我正在尝试熟悉sqlalchemy中的db.relatioships,这样我就可以构建允许更复杂查询的模型,并拥有“面向未来”的代码。
我似乎无法对这些关系进行正确的查询。 错误是在最后2个小循环中查询。这整个代码应该将'n paste右键复制到你的python提示符并运行。
有关获得此类查询的任何提示吗? (我希望这对经验丰富的开发人员来说是小菜一碟,不幸的是我不是开发人员。)
#!/usr/bin/python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_, and_
#http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://"
db = SQLAlchemy(app)
class Magazine(db.Model):
__tablename__ = 'tbl_magazine'
id = db.Column(db.Integer, primary_key=True)
magazineTitle = db.Column(db.String(120), unique=False, nullable=False)
magazineLanguage = db.Column(db.String(120), unique=False, nullable=False)
cover_id = db.Column(db.Integer, db.ForeignKey('tbl_cover.id'))
cover = db.relationship('Cover', back_populates='magazines')
class Cover(db.Model):
__tablename__ = 'tbl_cover'
id = db.Column(db.Integer, primary_key=True)
coverTitle = db.Column(db.String(120), unique=False, nullable=False)
coverAuthor = db.Column(db.String(120), unique=False, nullable=False)
magazines = db.relationship('Magazine', back_populates='cover')
db.create_all()
c0 = Cover(coverTitle = "FadingSun", coverAuthor="John" )
c1 = Cover(coverTitle = "FadingMoon", coverAuthor="John" )
c2 = Cover(coverTitle = "SportsCar", coverAuthor="Jack" )
db.session.add(c0)
db.session.add(c1)
db.session.add(c2)
db.session.commit()
m0 = Magazine(magazineTitle = "Times feb17",magazineLanguage = "French", cover_id=c0.id)
m1 = Magazine(magazineTitle = "Times feb17",magazineLanguage = "English", cover_id=c2.id)
m2 = Magazine(magazineTitle = "Times jan17",magazineLanguage = "English", cover_id=c0.id)
m3 = Magazine(magazineTitle = "Vogue feb17",magazineLanguage = "English", cover_id=c1.id)
m4 = Magazine(magazineTitle = "Spain oct16",magazineLanguage = "English", cover_id=c0.id)
db.session.add(m0)
db.session.add(m1)
db.session.add(m2)
db.session.add(m3)
db.session.add(m4)
db.session.commit()
print("lets get all magazine titles with fading sun")
for m in Magazine.query.filter(Magazine.cover.coverTitle == "FadingSun").all():
print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
print("lets get all magazine titles with fading sun in French")
for m in Magazine.query.filter(and_ (Magazine.cover.coverTitle == "FadingSun"), (Magazine.magazineLanguage == "French") ).all():
print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
print("lets get all cover titles that are on a magazine in English")
covers = {}
for m in Magazine.query.filter(Magazine.magazineLanguage == "English").all():
if m.cover.coverTitle in covers:
covers[m.cover.coverTitle] += 1
else:
covers[m.cover.coverTitle] = 1
for k,v in covers.iteritems():
print("%s occurs %s times on an english magazine"%(k,v))
P.S。我注意到最后一个DID工作,这是正确的方法吗?
主要错误在前2个查询中(如下面第一条评论中所要求的)
>>> print("lets get all magazine titles with fading sun")
lets get all magazine titles with fading sun
>>> for m in Magazine.query.filter(Magazine.cover.coverTitle == "FadingSun").all():
... print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 193, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Magazine.cover has an attribute 'coverTitle'
>>>
>>>
>>> print("lets get all magazine titles with fading sun in French")
lets get all magazine titles with fading sun in French
>>> for m in Magazine.query.filter(and_ (Magazine.cover.coverTitle == "FadingSun"), (Magazine.magazineLanguage == "French") ).all():
... print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 193, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Magazine.cover has an attribute 'coverTitle'
答案 0 :(得分:0)
可以使用.join()
修复前2个查询print("lets get all magazine titles with fading sun")
for m in db.session.query(Magazine).join(Magazine.cover).filter(Cover.coverTitle == "FadingSun").all():
print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
print("lets get all magazine titles with fading sun in French")
for m in db.session.query(Magazine).join(Magazine.cover).filter(and_ (Cover.coverTitle == "FadingSun"), (Magazine.magazineLanguage == "French") ).all():
print("%s has \"FadingSun\" coverTitle and was created by %s"%( m.magazineTitle,m.cover.coverAuthor ))
这些工作!