查询sql炼金术数据库时的KeyError

时间:2015-06-25 20:49:06

标签: python sql flask sqlalchemy flask-sqlalchemy

所以我有一本教育水平词典:

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])

然而,这给了我一个关键。我理解的是,当你看起来不是关键时,你就会发现错误。我100%确定我已经涵盖了数据库中所有可能的密钥。我甚至试图用这个搜索一些不在其键集中的东西:

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>

1 个答案:

答案 0 :(得分: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))