How to do query with `WHERE value IN list` in the Python Peewee ORM?

霸气de小男生 提交于 2019-12-10 02:02:16

问题


I'm using the (awesome) Python Peewee ORM for my Flask project, but I now got stuck trying to do a query with a where value in ['a', 'b', 'c']. I tried doing it as follows:

MyModel.select().where(MyModel.sell_currency in ['BTC', 'LTC'])

But unfortunately it returns all records in the DB. Any ideas how I could do this?


回答1:


The docs has the answer: x << y will perform x IN y, where y is a list or query. So the final query will look like:

MyModel.select().where(MyModel.sell_currency << ['BTC', 'LTC'])




回答2:


You can also do "IN" expressions with a subquery. For example, to get users whose username starts with "a":

a_users = User.select().where(fn.Lower(fn.Substr(User.username, 1, 1)) == 'a')

The .in_() method signifies an "IN" query

a_user_tweets = Tweet.select().where(Tweet.user.in_(a_users))

See http://peewee.readthedocs.io/en/latest/peewee/query_operators.html



来源:https://stackoverflow.com/questions/25179128/how-to-do-query-with-where-value-in-list-in-the-python-peewee-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!