On Tue, Oct 22, 2019, at 9:36 AM, Eric Lemoine wrote:
> Hi
>
> I want to use the FilteredQuery pattern [1], but I am facing a problem
> related to SQLAlchemy not calling "before_compile" as often as I'd expect it.
>
> Here's a simple example:
>
> @event.listens_for(Query, "before_compile", retval=True)
def before_compile(query):
print("XXXXX before_compiled called XXXXX")
return query
> class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
name = Column(String)
addresses = relationship("Address", back_populates="user")
class Address(Base):
__tablename__ = "address"
id = Column(Integer, primary_key=True)
email = Column(String)
user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", back_populates="addresses")
>
> and then I do the following twice:
>
> for u in Session().query(User):
for a in u.addresses:
print(u.name, a.email)
>
> The first time before_compile is called twice, one call for the SELECT FROM
> "user" query, and another call for the SELECT FROM "address" query. But the
> second time before_compile is called only once. It's called for the SELECT
> FROM "user" query, but not for the SELECT FROM "addresses" query. Is it
> expected?
>
> I am using SQLAlchemy 1.3.10.
sure, it sounds like u.addresses is already loaded. if you want u.addresses to
emit a query every time it is called you need to use the "dynamic" loader
strategy, that is, lazy="dynamic".
>
>
>
> The full test case is here:
> https://gist.github.com/elemoine/3fa86da54fc1195e314fa18999d05a68
>
>
>
> [1] https://github.com/sqlalchemy/sqlalchemy/wiki/FilteredQuery
>
> --
> 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 view this discussion on the web visit
> https://groups.google.com/d/msgid/sqlalchemy/ef750756-4a8e-4043-bd5e-873a188612ec%40googlegroups.com
>
> <https://groups.google.com/d/msgid/sqlalchemy/ef750756-4a8e-4043-bd5e-873a188612ec%40googlegroups.com?utm_medium=email&utm_source=footer>.
--
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 view this discussion on the web visit
https://groups.google.com/d/msgid/sqlalchemy/cbecca89-4ae3-4f5f-a0cf-75b1a2fb4af0%40www.fastmail.com.