'NoneType' 对象在尝试访问关系时没有属性 'owner'

'NoneType' object has no attribute 'owner' when trying to access relationship

我正在尝试在 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'

我错过了什么,我该如何解决?

.first() returns None 如果没有结果。因此,您对 clicked_toy 的查询未返回任何结果。

当您所做的只是过滤主键时,您可以使用 get 而不是 filter。 Flask-SQLAlchemy 更进一步,允许您在没有结果时引发 404。

clicked_toy = Toy.query.get_or_404(toy_id)