我正在尝试在Toy.owner
关系上加载一个值。这些是我的模特:
class User(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(50))
nickname = db.Column(db.String(255))
email = db.Column(db.String(255))
password = db.Column(db.String(255))
__mapper_args__ = {
"polymorphic_on":type,
'polymorphic_identity':'user',
'with_polymorphic':'*'
}
class Owner(User):
__tablename__ = 'Owner'
id = db.Column(db.Integer, db.ForeignKey('User.id', ondelete='CASCADE'), primary_key=True)
owner_id = db.Column(db.Integer, autoincrement=True, primary_key=True, unique=True)
toys = db.relationship('Toy', backref='owner', lazy='dynamic')
__mapper_args__ = {'polymorphic_identity':'owner'}
class Toy(db.Model):
__tablename__ = 'Toy'
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer, db.ForeignKey('Owner.owner_id'))
此视图应使用clicked_toy.owner_id
:
@app.route('/<path:toy_id>', methods=['GET','POST'])
def toy_info(toy_id):
clicked_toy = db.session.query(Toy).filter(Toy.id == toy_id).first()
owner = db.session.query(Owner).filter(Owner.owner_id == clicked_toy.owner.owner_id).first()
return render_template('toy_info.html', clicked_toy=clicked_toy, owner=owner)
这不起作用,我收到了错误:
File ".../controller.py", line 67, in toy_info
owner = db.session.query(Owner).filter(Owner.owner_id == clicked_toy.owner.owner_id).first()
AttributeError: 'NoneType' object has no attribute 'owner'
当我尝试拨打clicked_toy.owner_id
时,我收到同样的错误:
File ".../controller.py", line 67, in toy_info
owner = db.session.query(Owner).filter(Owner.owner_id == clicked_toy.owner_id).first()
AttributeError: 'NoneType' object has no attribute 'owner_id'
我缺少什么,我该如何解决?
答案 0 :(得分:1)
.first()
会返回None
。因此,您对clicked_toy
的查询未返回任何结果。
当你所做的只是过滤主键时,你可以使用get
而不是filter
。如果没有结果,Flask-SQLAlchemy更进一步允许你加注404。
clicked_toy = Toy.query.get_or_404(toy_id)