sqlalchemy不定長個OR條件如何查詢

#### 需求分析sql

需求是這樣的,我如今有一個列表,列表中的數據是這樣的數據庫

```sqlalchemy

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

```it

數據庫中有兩個字段`from_user_id`和`to_user_id`,我如今須要實現相似以下的查詢io

```import

wherefile

(from_user_id = a and to_user_id = b)model

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...

相關文章
相關標籤/搜索