Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy how LazyLoading works

Hi I would like to understand how does sqlalchemy lazy loading works? Assuming I have this query

results = (
        session.query(Parent).
            options(lazyload(Parent.children)).
            filter(Parent.id == 1).
            all()
    )

    for parent in results:
        logging.error(parent.children)

I want to know if I access the parent.children on the for loop will this create a new select statement? or is the record or parent.children already cached or something? I'm thinking of how this will affect the performance. I just want to most optimize way.

  1. Should I use lazyloading?
  2. Will accessing per item on the loop create a new sqlalchemy
  3. How do I find out if a query is being run by sqlalchemy? (Just want to find out if accessing per entry will create a select statement
like image 243
MadzQuestioning Avatar asked Oct 28 '25 03:10

MadzQuestioning


1 Answers

  1. Maybe.
  2. Do you mean issue a new query? The answer is yes, that's the point of lazyload(). The relationship collection attribute is populated when first accessed, lazily. If on the other hand you'd wish to avoid the possible N+1 situation, you could for example use joinedload() instead in order to populate children in the same query.
  3. Use logging. Pass echo=True in your engine configuration.
like image 56
Ilja Everilä Avatar answered Oct 29 '25 18:10

Ilja Everilä



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!