Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在SQLAlchemy中,with_实体和load_实体之间有什么区别?_Python_Sqlalchemy - Fatal编程技术网

Python 在SQLAlchemy中,with_实体和load_实体之间有什么区别?

Python 在SQLAlchemy中,with_实体和load_实体之间有什么区别?,python,sqlalchemy,Python,Sqlalchemy,查询数据库时,我只想加载指定的列。使用和\u实体创建查询需要引用模型列属性,而使用仅加载\u创建查询需要与列名对应的字符串。我更喜欢使用load_only,因为使用字符串创建动态查询更容易。这两者的区别是什么 有一些不同之处。当丢弃不需要的列(如问题中所述)时,最重要的一点是,仅使用load\u仍将导致创建对象(模型实例),而使用with\u entities只会获得具有所选列值的元组 >>> query = User.query >>> query.opt

查询数据库时,我只想加载指定的列。使用
和\u实体创建查询需要引用模型列属性,而使用
仅加载\u创建查询需要与列名对应的字符串。我更喜欢使用
load_only
,因为使用字符串创建动态查询更容易。这两者的区别是什么


有一些不同之处。当丢弃不需要的列(如问题中所述)时,最重要的一点是,仅使用
load\u
仍将导致创建对象(模型实例),而使用
with\u 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)]  
与联合国实体
with_entities()
可以添加或删除(简单地说:替换)模型;您甚至可以使用它修改查询,用自己的函数替换选定的实体,如
func.count()

请注意,生成的查询与
query.count()
的查询不同,后者可能较慢(因为它生成子查询)

with_实体的额外功能的另一个例子是:

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()
query=(
Page.query
.filter()
.join(Author.filter())
)
pages=query.all()
#好的,我拿到页面了。等等,什么?我也想要作者!
#如何在不再次生成查询的情况下执行此操作?
pages_和_authors=query.with_实体(Page,Author).all()
有些关联:
query = User.query
count_query = query.with_entities(func.count(User.id)))
count = count_query.scalar()
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()