【问题标题】:Querying in python peewee using combination of fields使用字段组合在 python peewee 中查询
【发布时间】:2016-10-26 11:52:14
【问题描述】:

我有一个包含字段 name:string 和 id_no:integer 的表,我从外部来源获得 name 和 id_no 列表,我需要使用 peewee ORM 获取具有此组合的记录。

例如:

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

为了获取具有上述数据组合的记录,我应该编写什么查询?

mysql中的类似查询:

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

【问题讨论】:

    标签: python mysql orm peewee


    【解决方案1】:

    我会这样写:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多