问题
I'm trying to load a value on the Toy.owner
relationshiop. These are my models:
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'))
This view should use 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)
This does not work, I got the error:
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'
When I tried to call clicked_toy.owner_id
instead, I got same error:
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'
What am I missing and how can I fix it?
回答1:
.first()
returns None
if there were no results. So your query for clicked_toy
returned no results.
You can use get
rather than filter
when all you're doing is filtering on the primary key. Flask-SQLAlchemy goes one step further by allowing you to raise 404 if there is no result.
clicked_toy = Toy.query.get_or_404(toy_id)
来源:https://stackoverflow.com/questions/28228002/nonetype-object-has-no-attribute-owner-when-trying-to-access-relationship