flask-SQLAlchemy:' NoneType'对象没有属性' filter_by'添加关系时出错

时间:2017-11-05 16:24:42

标签: python flask flask-sqlalchemy

我正在尝试为我的数据库创建以下结构:

我有一个父级UserModelChefModelCustomerModel为子级。一切正常,直到我尝试在OrderModel和两个类之间添加关系。我对UserModelChefModel的所有来电都收到以下错误消息。例如,当我试图找到一个厨师时:

    File "C:\Users\Moham\Documents\Food order\resources\chef.py", line 60, in get
    users = ChefModel.query.filter_by(active = True).all()
AttributeError: 'NoneType' object has no attribute 'filter_by'

这是我的ChefModel:

class ChefModel(UserModel):
    __tablename__ = 'chefs'
    id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key = True)
    food_items = db.relationship("FoodItemModel", backref="chef", lazy=True)
    __mapper_args__ = {'polymorphic_identity':'chefs'}

CustomerModel:

class CustomerModel(UserModel):
    __tablename__ = 'customers'
    id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key = True)   
    __mapper_args__ = {'polymorphic_identity':'customers'}

和OrderModel:

class OrderModel(db.Model):
    __tablename__ = 'orders'
    order_id = db.Column(db.Integer, primary_key = True)    
    updated_date = db.Column(db.DateTime, default=datetime.utcnow())
    description = db.Column(db.String(254)) 
    food_items = db.relationship("FoodItemModel", secondary = association_table)
    customer_id = db.relationship(db.Integer, db.ForeignKey('customers.id')) //if remove this line
    chef_id = db.relationship(db.Integer, db.ForeignKey('chefs.id')) //and this line, calls are normal

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为您在OrderModel中错误地指定了customer_id和chef_id列。尝试做这样的事情:

class OrderModel(db.Model):
    __tablename__ = 'orders'
    order_id = db.Column(db.Integer, primary_key = True)
    updated_date = db.Column(db.DateTime, default=datetime.utcnow())
    description = db.Column(db.String(254)) 
    customer_id = db.Column(db.Integer, db.ForeignKey("customers.id"))
    chef_id = db.Column(db.Integer, db.ForeignKey("chefs.id"))