Is there an option to make sqlalchemy populate foreign key column(s) when a 
relationship is set?
Basically I want the following:

child.parent = parent
assert child.parent_id == parent.id

Here is a full example you can run:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship


Base = declarative_base()


class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)


class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey(Parent.id), nullable=False)

    parent = relationship(Parent, backref='children')


engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)


def run():
    Base.metadata.create_all(engine)
    session = Session()
    parent1 = Parent(id=1)
    session.add(parent1)
    session.commit()


    child = Child(parent=parent1)
    print child.parent_id, ": None, but I'd like it to be 1"
    session.add(child)
    session.commit()


    parent2 = Parent(id=2)
    session.add(parent2)
    session.commit()
    child.parent = parent2
    t = child.parent_id, child.parent.id
    print t, ": child.parent_id is stale!"




if __name__ == '__main__':
    run()


-- 
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 https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to