查询SQLAlchemy数据库时出现KeyError

3

所以我有一个教育水平的字典:

education_levels = {
"Less than high school": 0,
"High school diploma or equivalent": 1,
"Postsecondary non-degree award": 2,
"Some college, no degree": 3,
"Associate's degree": 4,
"Bachelor's degree": 5,
"Master's degree": 6,
"Doctoral or professional degree": 7,
"#N/A": 100
}

我希望查询我的数据库,只显示等于或低于输入的教育水平的内容。
jobs = Occupation.query.filter(Occupation.area_name == area).filter(
    education_levels[Occupation.typical_entry_level_education] <= education_levels[education])

然而,这给了我一个关键错误。我知道关键错误是当您查找不是关键字的东西时发生的。我百分之百确定我已经涵盖了数据库中所有可能的关键字。我甚至尝试使用以下方法搜索不在关键字集中的内容:

def test():
jobs = Occupation.query.all()
job_list = []
for job in jobs:
    if not(job.typical_entry_level_education in education_levels.keys()):
        d = {
            'ed': job.typical_entry_level_education
        }
        job_list.append(d)
return job_list

我的test()函数输出的结果是这样的。
{
  "jobs": []
}

我无法理解为什么在所有的键都在键集中时,会出现键错误。我甚至在我的查询中尝试了布尔检查,但仍然出现错误。

这是我得到的错误(我确定它来自Occupation.typical_entry_level_education,因为我已经删除了后者,仍然出现错误):

education_levels[Occupation.typical_entry_level_education] <= education_levels[education])
KeyError: <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x3161e30>

请尝试查看以下内容:https://dev59.com/ZmvXa4cB1Zd3GeqPIVwv - Dušan Maďar
1个回答

1
问题在于您使用 SQLAlchemy 列作为键而不是其值。很遗憾,您无法像尝试的那样执行该查询。您可以在进行查询之前先获取有效值。
valid_levels = [k for k, v in education_levels.items() if v <= education_levels[education]]
jobs = Occupation.query.filter(Occupation.area_name == area).filter(Occupation.typical_entry_level_education.in_(valid_levels))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接