peewee选择在使用模型实例而不是直接使用模型时不工作的位置

2024-10-02 22:28:21 发布

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

我有一个peewee模型的实例my_table = MyTable(),我想从中选择一些模型实例。在

我不明白这为什么有用:

In  [0] [selection.p_name for selection in my_table.select() if selection.p_type == "Solar"] 
Out [0] ['Solar, photovoltaic',
         'Solar, photovoltaic',
         'Solar, photovoltaic',
         'Solar, photovoltaic',
         'Solar, concentrated solar power',
         'Solar, concentrated solar power']

但这并不是:

^{pr2}$

什么都不是输出。事实上,len(selections)=0

我做错什么了吗?在

我的模型定义在一个文件中,如下所示:

^{3}$

然后填充表。以下是SQLite数据库的屏幕截图,如DB Browswer for SQLite所示: enter image description here

然后创建一个表实例: 场景表=场景表()

然后,在Python shell中,导入实例:

from x.y import scenario_table

我知道它有我期望的所有模型实例(112):

>>> len(scenario_table.select())
112

这是有效的:

>>> [t.pathway_name for t in scenario_table.select() if t.pathway_type == 'Coal']
['Coal, sub-bituminous', 'Coal, bituminous', 'Coal, lignite', 'Coal, sub-bituminous', 'Coal, lignite', 'Coal, bituminous', 'Coal, bituminous', 'Coal, lignite']

但这并不是:

>>> [t.pathway_name for t in scenario_table.select().where(scenario_table.pathway_type == 'Coal')]
[]

经过反复试验,我能够通过直接导入模型而不是模型的实例来使事情正常进行。 所以,与其:

    from x.y import scenario_table

我现在有:

    from x.y import ScenarioTable  

现在:

selections = ScenarioTable.select().where(ScenarioTable.pathway_type=='Coal')
[t.pathway_name for t in selections]    

返回预期的模型实例名称列表。在

所以我现在的问题是:为什么模型实例select工作,而模型实例where不能工作?在


Tags: 实例namein模型fortypetableselect
1条回答
网友
1楼 · 发布于 2024-10-02 22:28:21

我想重现你的问题,但我做不到

首先创建数据库和表:

import peewee
db = peewee.SqliteDatabase('test.db')
db.connect()

class my_table(peewee.Model):
    p_name = peewee.CharField()
    p_type = peewee.CharField()

    class Meta:
        database = db
db.create_tables([my_table])

然后插入两行:

^{pr2}$

在那之后,我试试你的命令:

>>> [t.p_name for t in my_table.select().where(my_table.p_type=="Solar")]
['Solar, photovoltaic']

所以它在这里是有效的-也许你做了其他错误的事情,但你提供的代码是正确的

相关问题 更多 >