Skip to main content
 首页 » 编程设计

Python-SqlAlchemy。如何关联来自不同模块或文件的表

2025年05月04日10JeffreyZhao

我在同一个模块的一个文件中有这个类,在另一个文件中有项目类。如果在我定义新 channel 时它们位于不同的模块或文件中,则会出现错误,因为 Item 不在同一个文件中。我怎么解决这个问题?如果两个类都在同一个文件中,我不会收到任何错误。

ChannelTest.py

from ItemTest import Item 
 
metadata = rdb.MetaData() 
 
channel_items = Table( 
        "channel_items", 
        metadata, 
        Column("channel_id", Integer, 
            ForeignKey("channels.id")), 
        Column("item_id", Integer, 
            ForeignKey("items.id")) 
    ) 
 
class Channel(rdb.Model): 
    """ Set up channels table in the database """ 
    rdb.metadata(metadata) 
    rdb.tablename("channels") 
 
    id = Column("id", Integer, primary_key=True) 
    title = Column("title", String(100)) 
 
    items = relation("Item", 
                secondary=channel_items, backref="channels") 

Item.py 不同的文件,但在同一个模块中

class Item(rdb.Model): 
    """ Set up items table in the database """ 
    rdb.metadata(metadata) 
    rdb.tablename("items") 
 
    id = Column("id", Integer, primary_key=True) 
    title = Column("title", String(100)) 

提前致谢!

请您参考如下方法:

"NoReferencedTableError: Could not find table 'items' with which to generate a foreign key"

您所有的表定义都应该共享元数据对象。 所以你应该在一些单独的模块中执行 metadata = rdb.MetaData(),然后在所有 Table() 中使用这个 metadata 实例.