kewal kewal - 1 year ago 91
MySQL Question

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')

Answer Source

I'd write it as:

import operator

data = [
  {'name':'name1', 'id_no': 1},
  {'name':'name2', 'id_no': 2},
  {'name':'name3', 'id_no': 3},
conditions = [
  (( == item['name']) & (MyModel.id_no == item['id_no']))
  for item in data]
expr = reduce(operator.or_, conditions)
query =
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download