使用python和flask-sqlalchemy,如何使用动态变量作为列名从我的表中返回值?

2024-09-28 01:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

从我的数据库表中,我想返回多个值。每个值位于不同的行和列中。你知道吗

我使用for循环返回每一行。在每次循环中,我都能成功地将“year”值存储在字典中(state\u year\u dict)。这是因为'year'是我表中的一个列名。你知道吗

states = ['alabama', 'alaska', 'arizona', ... 'wisconsin', 'wyoming']
state_year_dict = {}
state_total_dict = {}
chosen_name = NameCounts.query.filter_by(name=name, gender=gender)
for state in states:
    state_high = chosen_name.order_by(getattr(NameCounts, state).desc()).first()
    state_year_dict[state] = state_high.year

在同一个循环中,我想存储当前在循环中使用的“state”中的值。但是,我不知道如何使用变量“state”来获取所需的值。这里有两个我尝试过的不起作用的例子。它们生成一个属性错误,表示模型没有属性“state”或“getattr”。你知道吗

state_total_dict[state] = state_high.state
state_total_dict[state] = state_high.getattr(BabyNameCountsA, state)

我到处找答案,运气都不好。任何见解都将不胜感激。你知道吗


Tags: name数据库forby属性genderyeardict

热门问题