Python Flask上的外键

时间:2014-04-21 12:16:48

标签: python flask

使用db模型获取此错误。知道可能是什么问题吗?

InvalidRequestError: When initializing mapper Mapper|Stand|stand, expression 'Stand.item_code_name==item_id' failed to locate a name ("name 'item_id' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.models.Stand'> class after both dependent classes have been defined.


class Stand(db.Model):
    stand_id = db.Column(db.String(10), primary_key = True) 
    stand_name = db.Column(db.String(24), index = True, unique = True)
    item_code_name =db.Column(db.String, db.ForeignKey('item_codes.item_id'))
    item_codes= db.relationship('Item_codes', primaryjoin = "Stand.item_code_name==item_id")  


class Item_codes(db.Model): 
    item_id = db.Column(db.String(10), primary_key = True)
    item_name = db.Column(db.String(100), index = True, unique = True)
    combi = db.Column(db.String(140))

1 个答案:

答案 0 :(得分:1)

映射器需要知道要加入的模型。

class Stand(db.Model):
    stand_id = db.Column(db.String(10), primary_key=True) 
    stand_name = db.Column(db.String(24), index=True, unique=True)
    item_code_name = db.Column(db.String, db.ForeignKey('item_codes.item_id'))
    item_codes = db.relationship('Item_codes', primaryjoin="Stand.item_code_name==Item_codes.item_id")

我还建议调用字段Stand.item_code_id(或其他内容)。使用_name我希望它加入Item_code.item_name