简体   繁体   中英

Python - SqlAlchemy. How to relate tables from different modules or files?

I have this class in one file and item class in another file in the same module. If they are in different modules or files when I define a new Channel, I got an error because Item is not in the same file. How can I solve this problem? If both classes are in the same file, I don't get any error.

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 Different file, but in the same module

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))

Thanks in advance!

The string method should work, but if it doesn't than there is also the option of simply importing the module.

And if that gives you import loops than you can still add the property after instantiating the class like this:

import item
Channel.items = relation(item.Item,
                         secondary=item.channel_items,
                         backref='channels')

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

All your table definitions should share metadata object. So you should do metadata = rdb.MetaData() in some separate module, and then use this metadata instance in ALL Table() 's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM