Skip to content

Instantly share code, notes, and snippets.

@Phaiax
Created May 23, 2019 19:35
Show Gist options
  • Save Phaiax/6f0c70adfd091a6c10280af72632b220 to your computer and use it in GitHub Desktop.
Save Phaiax/6f0c70adfd091a6c10280af72632b220 to your computer and use it in GitHub Desktop.
propchangesback
from sqlalchemy.orm import sessionmaker, relationship
class User(Base, HtmlEditable):
__tablename__ = 'user'
id = MyColumn(Integer, primary_key=True)
name = MyColumn(String, inputtype="text")
fullname = MyColumn(String, inputtype="text")
nickname = MyColumn(String)
large_enough = MyColumn(Boolean, inputtype="checkbox")
address_id = MyColumn(Integer, ForeignKey("address.id"))
address = relationship("Address", back_populates="people")
def __repr__(self):
return "<User(name='%s', fullname='%s', nickname='%s')>" % (
self.name, self.fullname, self.nickname)
def action_delete(self):
pass
class Address(Base, HtmlEditable):
__tablename__ = 'address'
id = MyColumn(Integer, primary_key=True)
street = MyColumn(String, inputtype="text")
people = relationship("User", back_populates="address")
people_json = MyColumn(String)
def __repr__(self):
return "<Address(street='%s', people_json='%s')>" % (
self.street, self.people_json)
def update_people_json(self):
j = []
for p in self.people:
j.append({"name":p.name, "large_enough": p.large_enough})
self.people_json = json.dumps(j)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
from sqlalchemy import event
@event.listens_for(Session, 'before_flush')
def receive_before_flush(session, flush_context, instances):
"listen for the 'before_flush' event"
print("before_flush!!!")
for instance in (session.new | session.dirty | session.deleted):
if isinstance(instance, User):
instance.address.update_people_json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment