What is the difference between with_entities and load_only in SQLAlchemy?

When querying my database, I want to load only the specified columns. To create a query using with_entities, a reference to the attribute of the model column is required, and when creating a query with load_only, a string corresponding to the column name is required. I would prefer to use load_onlyit because it’s easier to create a dynamic query using strings. What is the difference between the two?

load_only documentation

documentation with_entities

+4
source share
1 answer

. ( ) , load_only ( ), with_entities .

>>> query = User.query
>>> query.options(load_only('email', 'id')).all()
[<User 1 using e-mail: n@d.com>, <User 2 using e-mail: n@d.org>]
>>> query.with_entities(User.email, User.id).all()
[('n@d.org', 1), ('n@d.com', 2)]  

load_only

load_only() . . , ( ) .

" " , , , , . , :

User.query.options(load_only('name', 'fullname'))

with_entities

with_entities() (: ) ; , , func.count():

query = User.query
count_query = query.with_entities(func.count(User.id)))
count = count_query.scalar()

, query.count(), , , - MySQL ( ).

with_entities :

query = (
    Page.query
    .filter(<a lot of page filters>)
    .join(Author).filter(<some author filters>)
)
pages = query.all()

# ok, I got the pages. Wait, what? I want the authors too!
# how to do it without generating the query again?

pages_and_authors = query.with_entities(Page, Author).all()
+2

Source: https://habr.com/ru/post/1688978/


All Articles