Created
August 28, 2012 15:30
-
-
Save glenfant/3499127 to your computer and use it in GitHub Desktop.
sqlalchemy OrderingList issue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import sessionmaker, relationship | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.ext.orderinglist import ordering_list | |
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) | |
children = relationship('Child', backref='parent', | |
collection_class=ordering_list('position'), | |
order_by='Child.position' | |
) | |
class Child(Base): | |
__tablename__ = 'child' | |
id = Column(Integer, primary_key=True) | |
name = Column(Text) | |
position = Column(Integer) | |
parent_id = Column(Integer, ForeignKey('parent.id')) | |
def __repr__(self): | |
return "<Child id={0}, name={1}, position={2}>".format(self.id, self.name, self.position) | |
Base.metadata.create_all(sa_engine) | |
p = Parent() | |
session.add(p) | |
c1 = Child(name="aaa") | |
session.add(c1) | |
c2 = Child(name="ccc") | |
session.add(c2) | |
p.children.append(c1) | |
p.children.append(c2) | |
session.commit() | |
[parent] = session.query(Parent).all() | |
print parent.children | |
# -> [<Child id=1, name=aaa, position=0>, <Child id=2, name=ccc, position=1>] | |
c3 = Child(name="bbb") | |
session.add(c3) | |
parent.children.insert(1, c3) | |
print parent.children | |
# -> [<Child id=1, name=aaa, position=0>, <Child id=None, name=bbb, position=1>, <Child id=2, name=ccc, position=2>] | |
session.commit() | |
[parent] = session.query(Parent).all() | |
# Fixed, we keep now the children positions after a commit. | |
print parent.children | |
# -> [<Child id=1, name=aaa, position=0>, <Child id=3, name=bbb, position=1>, <Child id=2, name=ccc, position=2>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment