On 10 Feb 2015, at 22:14, Bao Niu <niuba...@gmail.com> wrote:
> 
> Why is assignment of a transient parent object does not automatically add 
> this parent object into the session? But Parent.append(PersistedChild) will 
> do the job nicely?
> Here is my code:
> 
> from sqlalchemy import Column, String, Integer, ForeignKey
> from sqlalchemy import create_engine
> from sqlalchemy.orm import sessionmaker
> from sqlalchemy.orm import relationship, backref
> from sqlalchemy.ext.declarative import declarative_base
> 
> Base = declarative_base()
> 
> class Department(Base):
>     __tablename__ = 'department'
>     id = Column(Integer, primary_key=True)
>     name = Column(String)
> 
> class Employee(Base):
>     __tablename__ = 'employee'
>     id = Column(Integer, primary_key=True)
>     name = Column(String)
>     department_id = Column(Integer, ForeignKey('department.id'))
>     department = relationship(Department, backref=backref('employees', 
> uselist=True))
> 
> engine = create_engine('sqlite:///')
> session = sessionmaker()
> session.configure(bind=engine)
> Base.metadata.create_all(engine)
> s = session()
> john = Employee(name='john')
> it_department = Department(name='IT')
> print(john in s) # should be False
> print(it_department in s) # should be False
> s.add(john)
> print(john in s) # should be True
> print(it_department in s) # should be False
> john.departments = it_department # here I expect it_department(the Parent 
> Object) would be automatically added to s in a cascade way, because of the 
> backref
> print(john in s) # should be True
> print(it_department in s) # should be True, however this is not true.
> 

I don’t know if this is the problem, but you appear to have a typo:

  john.departments = it_department

...but the relationship is called “department”, not “departments”

HTH,

Simon

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