开发者

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_i开发者_运维技巧d", 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!


"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 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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜