当前位置: 首页 > 后端技术 > Python

如何查询

时间:2023-03-26 11:35:12 Python

forsqlalchemyindeterminatelongORcondition####需求分析需求是这样的,我现在有一个列表,列表中的数据是这样的```[(a,b),(c,d),(e,f)...]```数据库中有`from_user_id`和`to_user_id`两个字段,我现在需要实现一个类似于下面的查询```where(from_user_id=aandto_user_id=b)or(from_user_id=candto_user_id=d)or(from_user_id=eandto_user_id=f)...```####解决方案-####方法1```fromsqlalchemyimporttuple_fromsqlalchemyimportor_,and_#modelisUserProfile#itemsarethe上面的列表,limit对于列表长度UserProfile.query.filter(tuple_(UserProfile.from_user_id,UserProfile.to_user_id).in_(items)).limit(limit)all()```这个[(a,),(b,),(c,),(d,),(e,),(f,)],即如果只有一个字段作为过滤条件,也可以像这样写```#列表必须是TupleUserProfile.query.filter(tuple_(UserProfile.from_user_id).in_(items)).limit(limit).all()```例子如下ows:```In[5]:UserProfile.query.filter(tuple_(UserProfile.id).in_([(14,),(232,)])).all()Out[5]:[,]```-####方法两个```条件=(and_(UserProfile.from_user_id==from_user_id,UserProfile.to_user_id==to_user_id)for(from_user_id,to_user_id)initems)UserProfile.query.filter(or_(*conditions)).limit(limit).all()```例子如下:```在[43]中:conditions=(and_(UserProfile.id==id,UserProfile.user_id==user_id)for(id,user_id)in[(14,'9ugy61mp3f'),(232,'9uh9u44uq1')])In[44]:UserProfile.query.filter(or_(*conditions)).all()Out[44]:[,]```如果只有一个字段作为过滤项,可以这样写```在[46]:conditions=(UserProfile.id==idforidin[14,232])In[47]:UserProfile.query.filter(or_(*conditions)).all()Out[47]:[,]```参考链接:[Howtogetrowsthatmatchalistof3-tuplesconditionswithSQLAlchemy](https://stackoverflow.com/que...