2015-02-08 82 views
0

我確實有這2個calsses ALS DB模式試圖將1 buidl許多關係:SQLAlchemy的關係錯誤

class User(db.Model): 
    __tablename__ = 'users' 
    id = db.Column(db.Integer, primary_key=True) 
    email = db.Column(db.String(255), index=True) #, unique=True) 
    firstname = db.Column(db.String(50)) 
    lastname = db.Column(db.String(50)) 

    bt_ids = db.relationship("BT", order_by="BT.id", backref="user") 



class BT(db.Model): 
    __tablename__ = 'bt' 
    id = db.Column(db.Integer, primary_key=True) 
    bt_id = db.Column(db.String(255), unique=True) 
    user_id = db.Column(db.Integer, db.ForeignKey('users.id')) 

    user = db.relationship("User", backref=db.backref('bt', order_by=id)) 

但我想我真的不明白建立關係的方式:

ArgumentError: Error creating backref 'user' on relationship 'User.bt_ids': property of that name exists on mapper 'Mapper|BT|bt' 

有什麼想法?

編輯

我其實是想通過user_id財產才達到類似的SQLAlchemy

class User(Base): 
    __tablename__ = 'users' 
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True) 
    name = Column(String(50)) 
    fullname = Column(String(50)) 
    password = Column(String(12)) 

    **addresses = relationship("Address", order_by="Address.id", backref="user")** 

    def __repr__(self): 
     return "<User(name='%s', fullname='%s', password='%s')>" % (
           self.name, self.fullname, self.password) 



class Address(Base): 
    __tablename__ = 'addresses' 
    id = Column(Integer, primary_key=True) 
    email_address = Column(String, nullable=False) 
    user_id = Column(Integer, ForeignKey('users.id')) 

    **user = relationship("User", backref=backref('addresses', order_by=id))** 

    def __repr__(self): 
     return "<Address(email_address='%s')>" % self.email_address 

回答

0

已經有UserBT之間的關係FK的例子的東西,所以你不能創建BT名爲user另一個關係。

class User(db.Model): 
    __tablename__ = 'users' 
    id = db.Column(db.Integer, primary_key=True) 
    email = db.Column(db.String(255), index=True) #, unique=True) 
    firstname = db.Column(db.String(50)) 
    lastname = db.Column(db.String(50)) 
    bts = db.relationship("BT", order_by="BT.id", backref="user") 

class BT(db.Model): 
    __tablename__ = 'bt' 
    id = db.Column(db.Integer, primary_key=True) 
    bt_id = db.Column(db.String(255), unique=True) 
    user_id = db.Column(db.Integer, db.ForeignKey('users.id')) 
+0

是的,它像你的建議一樣工作,但我試圖在sqlalchemy.org上實現類似上面的內容。 – Kev 2015-02-10 18:40:05

0

現在我知道了......

這是錯誤的:

用戶= db.relationship( 「用戶」,backref = db.backref( 'bt_ids',ORDER_BY = ID))

現在它的工作!