【问题标题】:flask-sqlalchemy dynamically construct queryflask-sqlalchemy 动态构造查询
【发布时间】:2019-07-15 22:45:25
【问题描述】:

我有一个像下面这样的输入 json:

{
  "page": 2,
  "limit": 10,
  "order": [
    {
      "field": "id",
      "type": "asc"
    },
    {
      "field": "email",
      "type": "desc"
    },
    ...
    {
      "field": "fieldN",
      "type": "desc"
    }
  ],
  "filter": [
      {
        "field": "company_id",
        "type": "=",
        "value": 1
      },
      ...
      {
        "field": "counter",
        "type": ">",
        "value": 5             
      }
  ]
}

如果我不知道字段数,如何根据输入的 json 动态构造 sqlalchemy 查询?

类似这样的:

User.query.filter(filter.field, filter.type, filter.value).filter(filter.field1, filter.type1, filter.value1)...filter(filter.fieldN, filter.typeN, filter.valueN).order_by("id", "ask").order_by("email", "desc").order_by("x1", "y1")....order_by("fieldN"...."desc").all()

【问题讨论】:

  • 转换成dict并使用key获取值?

标签: python json sqlalchemy flask-sqlalchemy


【解决方案1】:

将 json 转换为字典并检索值。

如果您的 json 在文件中(例如,data.json),则 json 库将满足您的需求:

import json

f = open("data.json")
data = json.load(f)
f.close()
User.query.filter(company_id=1).order_by(data["id"], data["ask"]).order_by(data["email"], data["desc"]).all()

如果你的 json 是一个字符串(比如,json_data):

import json

data = json.loads(json_data)
User.query.filter(company_id=1).order_by(data["id"], data["ask"]).order_by(data["email"], data["desc"]).all()

如果您的 json 是来自 python 请求库的请求,即res = requests.get(...),那么res.json() 将返回一个字典:

data = res.json()
User.query.filter(company_id=1).order_by(data["id"], data["ask"]).order_by(data["email"], data["desc"]).all()

【讨论】:

  • 哦,谢谢!如果有未知字段计数,例如 3 'order' 和 2 'filter'? Json 来自requests.get(...)。还是没有字段'order'和3个'filter'?
猜你喜欢
  • 2013-04-02
  • 2017-10-11
  • 2013-12-25
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2014-09-20
相关资源
最近更新 更多