2
我有兩個表,users
和contacts
。我查詢contacts
表並獲取用戶聯繫人列表。然後,我希望能夠編寫Contact.first_name
(其中first_name
是users
表中的一行),並打印出該聯繫人的名字。將多個外鍵映射到父表的問題
目前,我的Contact
對象不能識別user
表的任何屬性。
下面是一些代碼:
class User(Base):
""" Basic User definition """
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(Unicode(255))
last_name = Column(Unicode(255))
contacts = relationship('Contact', backref='users')
class Contact(Base):
__tablename__ = 'contacts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer)
contact_id = Column(Integer)
__table_args__ = (ForeignKeyConstraint([id], [User.id]), {})
這裏是我的查詢:
Contact.query.filter(Contact.user_id == self.user_id).filter(Contact.state == True).all()
說實話,我不能確定如何正確Contact.user_id
和Contact.contact_id
地圖我的兩個外鍵的User.id
行。也許這是我的問題的根源?
我對使用SQLAlchemy很新,所以這是一個學習體驗。謝謝你的幫助。