Skip to main content
 首页 » 编程设计

python之查询sql alchemy数据库时出现KeyError

2025年05月04日14kevingrace

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

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

但是,这给了我一个键盘错误。我知道一个 keyerror 是当你查找不是关键的东西时。我 100% 确定我已经涵盖了数据库中所有可能的 key 。我什至尝试使用以下方法搜索不在他们的键集中的内容:

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": [] 
} 

当一切都在键集中时,我无法理解我是如何得到一个键错误的。我什至在我的查询中尝试了 bool 检查,但它仍然给我错误

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

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

请您参考如下方法:

问题是您将 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))