sqlalchemy不定长个OR条件如何查询

码界遨游
• 阅读 3001

#### 需求分析

需求是这样的,我现在有一个列表,列表中的数据是这样的

```

[(a, b), (c, d), (e, f)...]

```

数据库中有两个字段`from_user_id`和`to_user_id`,我现在需要实现类似如下的查询

```

where

(from_user_id = a and to_user_id = b)

or (from_user_id = c and to_user_id = d)

or (from_user_id = e and to_user_id = f)

...

```

#### 解决方法

- #### 方法一

```

from sqlalchemy import tuple_

from sqlalchemy import or_, and_

# model为UserProfile

# items为上面的列表,limit为列表长度

UserProfile.query.filter(tuple_(UserProfile.from_user_id, UserProfile.to_user_id).in_(items)).limit(limit)all()

```

对于上面的方法,如果items是这样的[(a,), (b,), (c,), (d,), (e,), (f,)],即只有一个字段作为筛选条件的话,也可以这么写

```

# 列表里面一定得是元组

UserProfile.query.filter(tuple_(UserProfile.from_user_id).in_(items)).limit(limit).all()

```

示例如下:

```

In [5]: UserProfile.query.filter(tuple_(UserProfile.id).in_([(14,), (232,)])).all()

Out[5]: [<UserProfile 14>, <UserProfile 232>]

```

- #### 方法二

```

conditions = (and_(UserProfile.from_user_id==from_user_id, UserProfile.to_user_id==to_user_id) for (from_user_id, to_user_id) in items)

UserProfile.query.filter(or_(*conditions)).limit(limit).all()

```

示例如下:

```

In [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]: [<UserProfile 232>, <UserProfile 14>]

```

如果只有一个字段作为筛选项的话,可以像下面这样写

```

In [46]: conditions = (UserProfile.id==id for id in [14, 232])

In [47]: UserProfile.query.filter(or_(*conditions)).all()

Out[47]: [<UserProfile 232>, <UserProfile 14>]

```

参考链接:

[How to get rows which match a list of 3-tuples conditions with SQLAlchemy

](https://stackoverflow.com/que...

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Stella981 Stella981
4年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Wesley13 Wesley13
4年前
Java开发者容易犯的十个错误
!(https://oscimg.oschina.net/oscnet/c9f00cc918684fbe8a865119d104090b.gif)Top1.数组转换为数组列表将数组转换为数组列表,开发者经常会这样做:\java\List<StringlistArrays.asList(arr);Arr
Easter79 Easter79
4年前
SpringBoot自定义序列化的使用方式
场景及需求:项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串。例如:\    {        "id":1,        "name":null    },    {        "id":2,        "name":"x
Wesley13 Wesley13
4年前
MySQL总结(十一)子查询
!(https://oscimg.oschina.net/oscnet/upa344f41e81d3568e3310b5da00c57ced8ea.png)子查询1\.什么是子查询需求:查询开发部中有哪些员工selectfromemp;通
Stella981 Stella981
4年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
4年前
ThinkPHP 根据关联数据查询 hasWhere 的使用实例
很多时候,模型关联后需要根据关联的模型做查询。场景:广告表(ad),广告类型表(ad\_type),现在需要筛选出广告类型表中id字段为1且广告表中status为1的列表先看关联的设置部分 publicfunctionadType(){return$thisbelongsTo('A
Stella981 Stella981
4年前
Hibernate纯sql查询结果和该sql在数据库直接查询结果不一致
问题:今天在做一个查询的时候发现一个问题,我先在数据库实现了我需要的sql,然后我在代码中代码:selectdistinctd.id,d.name,COALESCE(c.count_num,0),COALESCE(c.count_fix,0),COALESCE(c
Stella981 Stella981
4年前
ELK学习笔记之ElasticSearch的索引详解
0x00ElasticSearch的索引和MySQL的索引方式对比Elasticsearch是通过Lucene的倒排索引技术实现比关系型数据库更快的过滤。特别是它对多条件的过滤支持非常好,比如年龄在18和30之间,性别为女性这样的组合查询。倒排索引很多地方都有介绍,但是其比关系型
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这