[英]SQLalchemy select all with optional attributes
与SQLalchemy我查询我的数据库。 我可以选择所有具有以下内容的行/对象:
def selectAllObjects():
objects = session.query(Object).all()
但是,我想构建一个函数来检查是否有给定的约束,以及是否包含这些约束。 所以我在考虑以下方面:
def selectAllObjects(attribute1="default",attribute2="default"):
if attribute1 != "default" and attribute2 != default:
objects = session.query(Object).filter_by(attribute1=attribute1,
attribute2=attribute2).all()
elif attribute1 != "default":
objects = session.query(Object).filter_by(attribute1=attribute1).all()
...etc, etc...
如您所见,当属性数量增加时,这变得非常难看。 pythonic的方法是什么?
Query
对象是可链接的,来自docs :
使用query()方法根据给定的会话产生查询:
q = session.query(SomeMappedClass)
所以你可以这样写:
def selectAllObjects(attribute1="default", attribute2="default"):
query = session.query(Object)
if attribute1 != "default" and attribute2 != "default":
query = query.filter_by(
attribute1=attribute1,
attribute2=attribute2,
)
elif attribute1 != "default":
query = query.filter_by(attribute1=attribute1)
return query.all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.