Trong user_models.py
, tôi có điều này:Trong SQLAlchemy, làm cách nào để tạo mối quan hệ ForeignKey trên 2 tệp .py khác nhau?
class Users(Base):
__tablename__ = 'account_users'
id = Column(Integer, primary_key = True)
username = Column(String(255), nullable=False)
Base.metadata.create_all(engine)
Khi tôi chạy này, tôi tạo ra một bảng dùng.
Mở tập tin khác của tôi, groups_models.py
, tôi có điều này:
class Groups(Base):
__tablename__ = 'personas_groups'
id = Column(Integer, primary_key = True)
user_id = Column(Integer, ForeignKey('account_users.id')) #This creates an error!!!
user = relationship('Users') #this probably won't work. But haven't hit this line yet.
Base.metadata.create_all(engine)
Vì vậy, như bạn thấy, tôi muốn đặt một-to-one nhiều mối quan hệ từ các nhóm -> người sử dụng.
Nhưng khi tôi chạy groups_models.py
... Tôi nhận được lỗi này:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'personas_groups.user_id' could not find table 'account_users' with which to generate a foreign key to target column 'id'
Nếu tôi đặt hai bảng với nhau trong một tập tin, tôi chắc chắn rằng nó có thể làm việc ... nhưng vì tôi chia nó vào 2 tập tin (mà tôi hoàn toàn phải) ... Tôi không biết làm thế nào để làm cho mối quan hệ ForeignKey làm việc nữa?
Đảm bảo rằng bạn có cùng một Cơ sở để tạo tất cả các bảng có liên quan !!!!! Tôi lãng phí nửa ngày vì lý do đó: / –