如何在SQLAlchemy中查询由JSON字符串组成的属性?

huangapple go评论85阅读模式
英文:

How to query over an attribute that consists of a string of JSON in SQLAlchemy?

问题

如你所见,metadata字段是字符串类型,包含明显是字符串的JSON数据。

现在,我想根据metadata的键来过滤结果,例如,我想返回那些metadata中participating设置为True的值。

类似于这样:

1, "London", "{'lat':51.5072, 'lon':0.1276, 'Mayor': 'Sadiq Khan', 'participating':True}",
3, "Manchester", "{'lat':53.4808, 'lon':2.2426, 'Mayor': 'Donna Ludford', 'participating':True}"

我尝试了以下方法:
db.session.query(City).filter(cast(eval(metadata['participating']), String) == True)

我收到了这个错误:
NotImplementedError: 运算符'getitem'不支持此表达式

我该如何实现所需的结果?

英文:

So, I table that looks like this.

City
id(Integer),
name(String),
metadata(String)

and it consists of data like this

1, "London", "{'lat':51.5072, 'lon':0.1276, 'Mayor': 'Sadiq Khan', 'participating':True}",
2, "Liverpool", "{'lat':53.4084, 'lon':2.9916, 'Mayor': 'Joanne Anderson', 'participating':"False},
3, "Manchester", "{'lat'53.4808, 'lon':2.2426, 'Mayor': 'Donna Ludford, 'participating':True}"

Now as you can see that the metadata field is of type string and consists of a JSON that is obviously a string.

Now, I want to filter the results based on the keys of metadata for example I want to return those values that have participating set to True in the metadata.

Something like this

1, "London", "{'lat':51.5072, 'lon':0.1276, 'Mayor': 'Sadiq Khan', 'participating':True}",
3, "Manchester", "{'lat'53.4808, 'lon':2.2426, 'Mayor': 'Donna Ludford, 'participating':True}"

I tried doing this
db.session.query(City).filter(cast(eval(metadata['participating]), String) == True)

I get this error
NotImplementedError: Operator 'getitem' is not supported on this expression

How do I achieve the desired result

答案1

得分: 0

你可以使用 Json 库:

  • 第一部分:
import json

# 获取所有数据
city_list = db.session.query(City).all()

创建筛选列表

filtered_city_list = []
  • 第二部分:
for city in city_list:
    metadata_dict = json.loads(city.metadata)
    if 'participating' in metadata_dict and metadata_dict['participating'] == True:
        filtered_city_list.append(city)

你可以将它们全部实现在一个函数中并使用它。

英文:

you can use Json lib:

  • First:
import json

# Get all Data
city_list = db.session.query(City).all()

Make filter list

filtered_city_list = []
  • Second:
    for city in city_list:
        metadata_dict = json.loads(city.metadata)
        if 'participating' in metadata_dict and metadata_dict['participating'] == True:
            filtered_city_list.append(city)

you can implement all of them in function and use it

答案2

得分: 0

Step:1 ==> 定义City表的模型类。

Step:2 ==> 定义用于根据元数据列中的'participating'值筛选城市的查询。

Step:3 ==> 获取参与的城市列表。

import json
from sqlalchemy import func

class City(Base):
    __tablename__ = 'City'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    metadata = Column(String)

participating_cities_query = db.session.query(City).filter(
    func.json_extract(City.metadata, '$.participating').cast(Boolean) == True
)

participating_cities = participating_cities_query.all()

for city in participating_cities:
    print(city.id, city.name, city.metadata)
英文:

Step:1 ==> Define the model class for the City table.

Step:2 ==> Define the query to filter the cities based on the 'participating' value in the metadata column.

Step:3 ==>Get the list of cities that are participating.

import json
from sqlalchemy import func


class City(Base):
    __tablename__ = 'City'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    metadata = Column(String)


participating_cities_query = db.session.query(City).filter(
    func.json_extract(City.metadata, '$.participating').cast(Boolean) == True
)


participating_cities = participating_cities_query.all()


for city in participating_cities:
    print(city.id, city.name, city.metadata)

huangapple
  • 本文由 发表于 2023年3月9日 14:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定