The elegance of sqlalchemy: variable field, variable length query

1. Unspecified field query

Assume that TbUser is a table model and session is a session with the database

An ordinary query might look like this:

session.query(TbUser).filter(TbUser.name=="xiaokeai")

This is a query designed to check the name field in TbUser . There is a need to check an entry with the letter y in a certain field, and a description of the unknown field appears.

__dict__ magic method : returns the attributes and attribute values ​​of the class item, the type is a dictionary. In the sqlalchemy model, the corresponding value of each normal field attribute is a field object, waiting to be instantiated when queried by a query.

# 一个模型的 __dict__ 参考
mappingproxy({
    
    '__module__': '__main__',
              '__tablename__': 'tb_user',
              'id': <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x638c5e8>,
              'name': <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x638c6a8>,
              ...以下省略...
              })

Use __dict__ to implement unspecified fields

col_name = "xxx"

# 查询某个字段包含有 xx 的 , 这个字段可能是任何一个字段
session.query(TbUser).filter(TbUser.__dict__[col_name].like("%y%"))
# 亦或者查询某个字段值等于 xx
session.query(TbUser).filter(TbUser.__dict__[col_name]=="xx")

2. Unspecified length query

session.query(TbUser).filter()  This is an ordinary filter query. In fact, all conditions in the filter are an object, and a list is used to install all query condition objects.

filters = [
	TbUser.name.like("y")	# 加一个包含条件
	TbUser.xx=="test"		# 加一个值等于的条件
]

# 可以直接对过滤条件解包
session.query(TbUser).filter(*filters)

and_, or_ increase example

# 查询同时满足有filters内条件的
session.query(TblSymp).filter(and_(*filters),)

# 查询同时满足filters条件的 或者满足 filters2 条件的
session.query(TbUser).filter(or_(and_(*filters), *filters2))

I'm just a idiot, and your likes will be my biggest motivation for updating.

Guess you like

Origin blog.csdn.net/qq_39177678/article/details/107512138