Question

Trying to create an association relationship between the classes Note and Document. The problem I'm facing is that my secondary relationship only works when I use the association table object and not that table name. What I mean is that the relationship:

notes = relationship(u'Note', secondary=t_Documented, backref='documents')

works but the following does NOT work:

notes = relationship(u'Note', secondary='Documented', backref='documents')

When querying, I get the error:

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Document|Document, expression 'Documented' failed to locate a name ("name 'Documented' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.

I would rather use the name as my model is generated using sqlacodegen.

Moreover, SQLAlchemy docs say I can use the name (http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many) with caveta "with the declarative extension in use". I Googled the term which led me to this. Question is how in my case can I augment the Base.

# model.py
# coding: utf-8
from sqlalchemy import Column, Date, DateTime, ForeignKey, ForeignKeyConstraint, Index, Integer, Numeric, String, Table, Text, text
from sqlalchemy.orm import backref, relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata

t_Documented = Table(
    'Documented', metadata,
    Column('id', Integer, primary_key=True),
    Column('note_id', ForeignKey(u'MySchema.Note.id'), nullable=False),
    Column('document_id', ForeignKey(u'MySchema.Document.id'), nullable=False, index=True),
    Column('inserted', DateTime, nullable=False, server_default=text("'0000-00-00 00:00:00'")),
    Column('updated', DateTime, nullable=False, server_default=text("'0000-00-00 00:00:00'")),
    Index('Documented_AK1', 'note_id', 'document_id'),
    schema='MySchema'
)

class Note(Base):
    __tablename__ = 'Note'
    __table_args__ = {u'schema': 'MySchema'}

    id = Column(Integer, primary_key=True)

class Document(Note):
    __tablename__ = 'Document'
    __table_args__ = {u'schema': 'MySchema'}

    id = Column(ForeignKey(u'MySchema.Note.id'), primary_key=True)
    title = Column(String(100), nullable=False)
    author = Column(String(100), nullable=False)

    notes = relationship(u'Note', secondary='Documented', backref='documents')

Using SQLAlchemy 0.9.4 and Python 2.6.6. Connector is MySQLDB and I'm using MySQL database.

Was it helpful?

Solution

your table has a schema of "MySchema" so that has to be part of it:

notes = relationship(u'Note', secondary='MySchema.Documented', backref='documents')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top