kewal
kewal

Reputation: 111

Querying in python peewee using combination of fields

I have a table with fields name:string and id_no:integer, from an external source I get list of name and id_no, I need to fetch the records with this combination using peewee ORM.

for example:

input = [
{'name':'name1', 'id_no': 1},
{'name':'name2', 'id_no': 2},
{'name':'name3', 'id_no': 3},
]

What query do I write in order to fetch records with above mentioned combination of data?

Similar query in mysql:

SELECT * FROM table_name
WHERE CONCAT(convert(id_no, char), ':', name) IN ('1:name1','2:name2','3:name3')

Upvotes: 2

Views: 461

Answers (1)

coleifer
coleifer

Reputation: 26245

I'd write it as:

import operator

data = [
  {'name':'name1', 'id_no': 1},
  {'name':'name2', 'id_no': 2},
  {'name':'name3', 'id_no': 3},
]
conditions = [
  ((MyModel.name == item['name']) & (MyModel.id_no == item['id_no']))
  for item in data]
expr = reduce(operator.or_, conditions)
query = MyModel.select().where(expr)

Upvotes: 2

Related Questions