Hi *,
this post is a bit short on data because I just wrote a long posting and it
seems to have vanished when I hit the "POST" button. *sigh*
I am trying to do something (admittedly crazy) like this, but without the
after_flush hook - I'd rather like to tell the ORM that member_ids is
computed from the members list.
Problem is that entries to members are new at the time of flush, so ids are
not available.
Any hints how to create a new csv_relationship property to track the ids of
referred objects in a column of comma separated values?!
from sqlalchemy import create_engine, Column, Integer, String, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Person(Base):
__tablename__ = "persons"
id = Column(Integer, primary_key=True)
name = Column(String)
class Bundle(Base):
__tablename__ = "bundle"
id = Column(Integer, primary_key=True)
member_ids = Column(String, unique=True)
def __init__(self, members):
self.members = members
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
@event.listens_for(Session, "after_flush")
def receive_after_flush(session, flush_context):
items = set(session.dirty) | set(session.new)
for item in items:
if isinstance(item, Bundle):
session.execute(Bundle.__table__
.update()
.values(member_ids=",".join(str(x.id) for x in item.members
))
.where(Bundle.id == item.id))
session = Session()
persons = [Person(name=name) for name in ["Martin", "Michael", "Fabian"]]
for person in persons:
session.add(person)
session.commit()
bundle = Bundle(persons[1:])
session.add(bundle)
session.commit()
Thanks and Greetings, Torsten
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.