Thanks, just what I needed.

    -Jim

On 10/12/2010 9:38 AM, Conor wrote:
On 10/12/2010 09:20 AM, Jim Steil wrote:
 Hi

Using SQLAlchemy 0.5.8.

I have the following model...


class Link(DeclarativeBase):
    __tablename__ = 'link'

    linkId = Column(Integer, autoincrement=True, primary_key=True)
    name = Column(Unicode(50), nullable=False)
    parentLinkId = Column(Integer, ForeignKey('link.linkId'))
    url = Column(Unicode(255))
permissionId = Column(Integer, ForeignKey('tg_permission.permission_id'))
    description = Column(Text())
    parentLink = relation(Link, primaryjoin=parentLinkId==Link.linkId)
permission = relation(Permission, primaryjoin=permissionId==Permission.permission_id)

The problem is with the second to the last line. I'm trying to create a relation to point to the parent link, which points back to the same table. I'm using TurboGears and when I try to start my server I get the following error:

parentLink = relation(Link, primaryjoin=parentLinkId==Link.linkId)
NameError: name 'Link' is not defined

I'm new to SA.  Can someone help me out with this relation?

Due to Python semantics, "Link" is not bound to anything until the class definition is complete. The get around this, SQLAlchemy provides several options:

   1. In this case, you can simply use parentLinkId==linkId as the
      primaryjoin.
   2. You can wrap the primaryjoin in a function/lambda, e.g.
      primaryjoin=lambda: Link.parentLinkId==Link.LinkId. SQLAlchemy
      will call this function sometime after the class definition is
      complete, at which point "Link" is bound to something.
   3. You can use a string as the primaryjoin, e.g.
      primaryjoin="Link.parentLinkId==Link.linkId". SQLAlchemy will
      evaluate this expression similar to option #2.

In any case, you need to include a remote_side argument to the relation to indicate that this is the many-to-one side of the relationship[1], e.g.
parentLink = relation(Link, primaryjoin=lambda: Link.parentLinkId==Link.linkId, 
remote_side=lambda: [Link.linkId])

-Conor

[1]: http://www.sqlalchemy.org/docs/orm/relationships.html?highlight=remote_side#adjacency-list-relationships

--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.

--
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to