Why is assignment of a transient parent object does not automatically add this parent object into the session?

14 views
Skip to first unread message

Bao Niu

unread,
Feb 10, 2015, 5:14:52 PM2/10/15
to sqlal...@googlegroups.com
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.

Simon King

unread,
Feb 10, 2015, 5:37:11 PM2/10/15
to sqlal...@googlegroups.com
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

Bao Niu

unread,
Feb 11, 2015, 12:59:18 AM2/11/15
to sqlal...@googlegroups.com
I guess what I must do immediately is to get myself a pair of new glasses...Thank you Simon!


--
You received this message because you are subscribed to a topic in the Google Groups "sqlalchemy" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sqlalchemy/3EE9dZHpNj4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages