python - 访问在 sqlalchemy 中没有 key 的 json

标签 python postgresql sqlalchemy

我有一列“”,类型为 postgres“JSON”。 列中的示例数据。

  1. “显示名称 1”
  2. {"middleName": "其他"}
  3. [{"primary": true, "type": "work", "value": "rusr@r.com"}, {"primary": true, "type": "work", "value": "iu@n.com"}]

我知道我可以像这样使用键值对访问 json,

.filter(Values.value['middleName'].astext=='other')(values 是模型名称)

问题是如何访问字符串值或对象数组。

我试过了,

.filter(Values.value.astext=='displayname1') 它给我 AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Values.value has an attribute 'astext'

.filter(Values.value['type'].astext=='work')- 我在这里尝试过滤数组中的“type”:“work”对象。你怎么做到这一点。是否可以在不指定索引的情况下搜索所有对象。

我正在使用 postgres 作为后端数据库。

模型 -

class Values(db.Model):
    __tablename__ = 'attribute_values'
                    
    id = db.Column(db.Integer, primary_key=True)
    attribute = db.Column(db.Integer, ForeignKey('attributes.id'), primary_key=True)
    value = db.Column(JSON)
class Attributes(db.Model):
    __tablename__ = 'attributes'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)

   user_attribute = db.relationship(Values, backref='attributes', primaryjoin=id == Values.attribute)

查询我正在尝试-

db.session.query(Values).join(Attributes, Values.attribute == Attributes.id).filter("what filters that i should be using for the cases mentioned above").all()

最佳答案

假设json对象是一个字符串,使用json.loads将其转换为字典然后正常索引。

>>> import json
>>> s = """[{"primary": true, "type": "work", "value": "rusr@r.com"}, {"primary": true, "type": "work", "value": "iu@n.com"}]"""
>>> my_dict = json.loads(s)
>>> my_dict[0]['type']
'work'

然后您可以使用以下列表理解搜索 type == 工作的任何行。

>>> search = [i for i in my_dict if i['type'] == 'work']
>>> search
[{'primary': True, 'type': 'work', 'value': 'rusr@r.com'}, {'primary': True, 'type': 'work', 'value': 'iu@n.com'}]

这是不使用列表推导式的同一事物的示例。

>>> search = list()
>>> for i in my_dict:
...     if i['type'] == 'work':
...             search.append(i)
...
>>> search
[{'primary': True, 'type': 'work', 'value': 'rusr@r.com'}, {'primary': True, 'type': 'work', 'value': 'iu@n.com'}]

关于python - 访问在 sqlalchemy 中没有 key 的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916064/

相关文章:

python - 使用存储过程保持 ORM

python - Pyramid 架构迁移

c++ - 基准测试(python 与使用 BLAS 的 c++)和(numpy)

python - 用 keras 尝试 Kaggle Titanic .. 得到损失和 valid_loss -0.0000

python - Django 2 url路径匹配负值

sql - PostgreSQL - 从 bash 脚本查询数据库用户 'postgres'

python 编码问题\ufeff in pandas 列名

postgresql - 在 PL/R 中加载、列出和使用 R 模块和函数

sql - postgresql 9.4/9.5 - 选择...更新具有高读取和写入的大型数据集上的单个随机行

python - 无法使用 SqlAlchemy pickle 对象错误