Hi Wayne.
El 02/06/17 a las 06:43, Wayne escribió:
Hi,
Does anyone have any experience, links to open source code or anything
else that shows the integration of PyQT5 with SQLAlchemy?
I'm using SQLAlchemy with PyQt4. My experience is valid for PyQt5 using
QtWidgets module, QtQuick is a different beast.
There are a couple of frameworks available like
http://www.python-camelot.com/, but I'm using my own library to use my
Python models with PyQt4: UI https://bitbucket.org/shulai/qonda.
My workflow is something like this:
* I create a session and retrieve the models I need to setup a window.
The session must be closed before returning to the event loop, so I must
retrieve anything I need either using eager loading options in queries,
forcing lazy loading in Python code, or (if you bind the model to the UI
using Qt Model-View [e.g. using Qonda]) forcing lazy loading calling
repaint(). If you fail to do this, you'll get an error like this:
DetachedInstanceError: Parent instance <Socio at 0x7f7473bd4240> is not
bound to a Session; lazy load operation of attribute 'persona' cannot
proceed
Probably the better way to handle sessions in modern Python is with the
following idiom.
from contextlib import closing
...
with closing(Session()) as session:
model = session.query()...
you can also use:
session = Session()
try:
model = session.query()...
...
finally:
session.close()
* I can do more queries in events, like a search, using a new, event
bound session. As using different sessions yields different Python
objects for the same identity, you must be careful. Sometimes at least
you need to define __eq__ and __hash__ for certain models:
class Prestador(Base, ObservableObject):
...
def __eq__(self, other):
if not isinstance(other, Prestador):
return False
return self.id == other.id
def __hash__(self):
# Redefining __eq__ required redefining __hash__
if self.id:
return self.id # Warning: Probably too naive
# If not persisted
return Base.__hash__(self)
* To save new objects, creating a new session, adding the object and
commiting is sufficient. To update objects retrieved earlier I use
session.merge(). A while ago Mike suggested using the command pattern,
recording all the UI actions and replaying on the save session, but
implementing the pattern is a lot of extra work.
Thanks
Wayne
Greetings. Julio.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
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.