views:

34

answers:

2

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!

A: 

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')
WoLpH
I'd already tried that. I don't know what's going on. This is the error if I try what you said:"NoReferencedTableError: Could not find table 'items' with which to generate a foreign key"Al least it's different error and if can find the class because the name of the table is items (class Item). So I guess I'm missing somethingThanks!
bribon
Unfortunately I'm not too familiar with rdb. I know that this works for plain SQLAlchemy classes. Perhaps you're still missing an import so it can find the other class?Try importing `Item.py` from `ChannelTest.py` and vice versa. That just might fix it ;)
WoLpH
A: 

"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.

Daniel Kluev