On Dec 5, 2011, at 9:57 PM, Rivka Shenhav wrote:

> Michael,
> 
> Thanks so much for your prompt answer. Instead of going into the extensive 
> details of my program - I decided to abstract from it and 
> just try to get down the basic operations of the construct. So - I wrote a 
> very simple tutorial that pretty much implements what the
> documentation recommends (Pg. 81 together with the stuff from pg. 71)
> 
> class Ref_Association(Base):
>     __table__= Table('article_xrefs', Base.metadata,
>     Column('referencing_id', Integer, ForeignKey("articles.article_id"), 
> primary_key=True),
>     Column('referenced_id', Integer, ForeignKey("articles.article_id"), 
> primary_key=True),
>     Column('info', String)
>     )
>     
> 
> class Article(Base):
>     __tablename__='articles'
>     article_id = Column(Integer, primary_key=True)
>     headline = Column(String(150))
>     body = Column(String)
>     
>     references = relationship("Article",
>                              secondary=Ref_Association.__table__,
>                              primaryjoin= 
> article_id==Ref_Association.__table__.c.referencing_id,
>                              secondaryjoin= 
> article_id==Ref_Association.__table__.c.referenced_id,
>                              backref="referencing")
>     
> r_assoc1 = Ref_Association()
> a1.references.append(r_assoc1)

so you're mixing up the roles of Article and Ref_Association here.   
Article.references expects an Article, not a Ref_Association.   To use it 
correctly given this setup:

a1.references.append(a2)

where a2 is also an Article.

However, it appears you'd like the association between Articles to be mapped to 
Ref_Association, and have explicit access to this table (which is because you 
also have "info" set up).  This then becomes the association object patern, In 
which case the "references" and "referencing" relationships need to be broken 
out into two separate relationships to Ref_Association:

references = relationship(Ref_Association, primaryjoin= 
article_id==Ref_Association.referencing_id, backref="referencing_article")
referencing = relationship(Ref_Association, primaryjoin= 
article_id==Ref_Association.referenced_id, backref="referenced_article")

That is, A<-->RA<-->A - each <--> is a relationship with a backref.  There's no 
usage of "secondary" here.     (You can make a totally separate relationship 
that uses "secondary" for performance reasons, as the SQL emitted is simpler 
when it loads, but I'd make it viewonly=True).

Once you get familiar with this setup, you then introduce the association 
proxy:  http://www.sqlalchemy.org/docs/orm/extensions/associationproxy.html to 
reduce verbosity for basic operations between related Article objects.


Attachment: PGP.sig
Description: This is a digitally signed message part

Reply via email to