13

I'm trying to make a self-referential many-to-many relationship (it means that Line can have many parent lines and many child lines) in sqlalchemy like this:

Base = declarative_base()

class Association(Base):
 __tablename__ = 'association'

 prev_id = Column(Integer, ForeignKey('line.id'), primary_key=True)                            
 next_id = Column(Integer, ForeignKey('line.id'), primary_key=True)


class Line(Base):
 __tablename__ = 'line'

 id = Column(Integer, primary_key = True)
 text = Column(Text)
 condition = Column(Text)
 action = Column(Text)

 next_lines = relationship(Association, backref="prev_lines")



class Root(Base):
 __tablename__ = 'root'

 name = Column(String, primary_key = True)
 start_line_id = Column(Integer, ForeignKey('line.id'))

 start_line = relationship('Line')

But I get the following error: sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/ child tables on relationship Line.next_lines. Specify a 'primaryjoin' expressio n. If 'secondary' is present, 'secondaryjoin' is needed as well.

Do you know how I could remedy this?

1
  • I tried this: next_lines = relationship(Association, backref="prev_lines", primaryjoin=id==Association.next_id) prev_lines = relationship(Association, backref="next_lines", primaryjoin=id==Association.prev_id) Now it does not produce any error. Is it a correct solution? Or will it produce other problems?
    – mike
    Nov 14, 2010 at 12:03

1 Answer 1

7

You should just need:

prev_lines = relationship(
    Association,
    backref="next_lines",
    primaryjoin=id==Association.prev_id)

Since this specifies the next_lines back reference there is no need to have a next_lines relationship.

You can also do this using the remote_side parameter to a relationship: http://www.sqlalchemy.org/trac/browser/examples/adjacency_list/adjacency_list.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.