Related to one of my recent posted threads here, I'm recalling a certain
conversation at PyCon where I was mentioning how a friend would define
a many-to-many relationship by defining a relationship on both declarative
classes involved, each pointing to the other, and the look of abject horror
I received gave a good indication that this is very often not a good thing.
However, I've run into a situation where this has proven useful:

class Deployment(Base):
    __tablename__ = 'deployments'

    id = Column(u'DeploymentID', INTEGER(), primary_key=True)
    package_id = Column(
        INTEGER(),
        ForeignKey('packages.package_id', ondelete='cascade'),
        nullable=False
    )

    package = relationship('Package')


class Package(Base):
    __tablename__ = 'packages'

    id = Column(u'package_id', INTEGER(), primary_key=True)
    pkg_name = Column(String(length=255), nullable=False)
    version = Column(String(length=63), nullable=False)
    revision = Column(String(length=63), nullable=False)

    deployments = relationship('Deployment')

In this case, most of the time I'm looking to determine which deployments
a given package belongs to, but there are times when I have a given
deployment and am curious as to what package(s) are related to it, and
unless I'm misunderstanding something (which I won't rule out I could
be), a backref won't easily help in this instance.

Of course, one of the gotchas in using this (and we did hit it in one of
our queries) is if not careful, one can trigger a nice 'maximum recursion
depth exceeded' exception (in our particular case, a 'joinedload' within
the query was able to resolve that issue) and I'm sure there other poten-
tial "gotchas", so I guess this leads back to the main question at hand:

Are there times when using "reciprocal" relationships is okay, and are
there certain things that should be done to mitigate potential issues that
can be caused by doing so, or are there better ways to accomplish the
same thing?

-- 
- Ken Lareau

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to