Brian Leach
Brian Leach

Reputation: 4154

SQLAlchemy adjacency list relationship with declared attributes

I have a Top level model declaration that is inherited by different types of children

class HasId(object):

    @declared_attr
    def id(cls):
        return Column('id', Integer, Sequence('test_id_seq'), primary_key=True)
    ...
    @declared_attr
        def triggered_by_id(cls):
            return Column(Integer, ForeignKey('tests.id'), nullable=True)

    @declared_attr
        def triggered(cls):
            return relationship('TestParent',
                                foreign_keys='TestParent.triggered_by_id',
                                lazy='joined',
                                cascade='save-update, merge, delete, delete-orphan',
                                backref=backref('triggered_by', remote_side=[id])
                                )


class TestParent(HasId, Model):
    __tablename__ = 'tests'

    discriminator = Column(String(50))

    __mapper_args__ = {'polymorphic_on': discriminator}


class FooTest(TestParent):
    __tablename__ = 'footests'
    __mapper_args__ = {'polymorphic_identity': 'footests'}
    id = Column(Integer, ForeignKey('tests.id'), primary_key=True)

    bar = Column(Boolean)
    ...

When IO try to build this database, I get an error caused by how I have defined the remote_side of the backref on the triggered_by relationship.

The full error is

ArgumentError: Column-based expression object expected for argument 'remote_side'; got: '<built-in function id>', type <type 'builtin_function_or_method'>

Upvotes: 4

Views: 2958

Answers (1)

Brian Leach
Brian Leach

Reputation: 4154

The solution is to change the backref definition from

backref('triggered', remote_side=[id])

to

backref('triggered', remote_side='TestParent.id')

Upvotes: 11

Related Questions