尝试访问关系时,"NoneType"对象没有属性“所有者" [英] 'NoneType' object has no attribute 'owner' when trying to access relationship

查看:85
本文介绍了尝试访问关系时,"NoneType"对象没有属性“所有者"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Toy.owner Relationshiop上加载一个值.这些是我的模型:

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'))

此视图应使用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'

当我尝试致电clicked_toy.owner_id时,出现了相同的错误:

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?

推荐答案

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

.first() returns None if there were no results. So your query for clicked_toy returned no results.

当您要做的只是对主键进行筛选时,可以使用get而不是filter.如果没有结果,Flask-SQLAlchemy进一步允许您提高404,从而更进一步.

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)

这篇关于尝试访问关系时,"NoneType"对象没有属性“所有者"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆