Hi all!
I'm trying to use sqlalchemy.ext.orderinglist as per instructions here
<http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/orderinglist.html> ,
and but I've encountered a loss of data while trying to swap positions of
related records inside a related property list. I thought it was related to
sqlalchemy.ext.orderinglist, but when I excluded it the situation remained
the same. Here is the full not-so-working example:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Text, ForeignKey
sa_engine = create_engine("sqlite:///:memory:")
Session = sessionmaker(bind=sa_engine)
session = Session()
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(Text)
children = relationship('Child', backref='parent')
def __repr__(self):
return self.name
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
name = Column(Text)
parent_id = Column(Integer, ForeignKey('parent.id'))
def __repr__(self):
return self.name
Base.metadata.create_all(sa_engine)
p = Parent(name='Thomas')
session.add(p)
c1 = Child(name="Mary")
c2 = Child(name="John")
c3 = Child(name="Kenny")
p.children.append(c1)
p.children.append(c2)
p.children.append(c3)
session.commit()
p = session.query(Parent).get(1)
print(p.children) #prints [Mary, John, Kenny]
p.children[1], p.children[2] = p.children[2], p.children[1]
print(p.children) #prints [Mary, Kenny, John]
session.commit()
print(p.children) #prints [Mary, John]. Oh my God! They killed Kenny!
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.