back_populate solves this.

Full Example:

from sqlalchemy import create_engine, Column, ForeignKey, Integerfrom 
sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import 
relationship, sessionmaker

Base = declarative_base()
## Modelclass Parent(Base):
    __tablename__ = 'parents'
    id = Column(Integer(), primary_key=True, autoincrement=True)
    childs = relationship("Child", primaryjoin="or_(Child.father_id==Parent.id, 
Child.mother_id==Parent.id)")
class Child(Base):
    __tablename__ = 'children'
    id = Column(Integer(), primary_key=True, autoincrement=True)
    father_id = Column(Integer(), ForeignKey('parents.id'))
    mother_id = Column(Integer(), ForeignKey('parents.id'))
    
    father = relationship("Parent", foreign_keys=[father_id], 
back_populates="childs")
    mother = relationship("Parent", foreign_keys=[mother_id], 
back_populates="childs")

        
engine = create_engine('sqlite:///sqlite.db')
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine, autoflush=False, autocommit=False, 
expire_on_commit=False)
session = DBSession()

## Test Code
father = Parent()assert len(father.childs) == 0 # SUCCESS

mother = Parent()
c1 = Child(father=father, mother=mother)assert c1.father is father              
# SUCCESSassert c1.mother is mother             # SUCCESS

session.add_all([father, mother, c1])
session.commit()
# Using refresh solves the assertion#session.refresh(father)assert 
len(father.childs) > 0       # SUCCESSassert father.childs == [c1]   # 
SUCCESSassert mother.childs == [c1]   # SUCCESS





On Thursday, September 17, 2015 at 8:43:51 PM UTC+3, Jonathan Vanasco wrote:
>
> Immediately I notice that the attributes  `father`/`mother` have no 
> relationship to the `Parent` object.  I think specifying 
> backref/back_populates should solve your issue:   
> http://docs.sqlalchemy.org/en/rel_1_0/orm/backref.html
>
>
> Also, FYI
>
> You can use `expire` on just the relationships (
> http://docs.sqlalchemy.org/en/rel_1_0/orm/session_api.html#sqlalchemy.orm.session.Session.expire
> )
>
>     session.expire(father, ['childs',])
>
>

-- 
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