Skip to main content
 首页 » 编程设计

Python orm 日期时间问题

2025年05月04日13zhujiabin

我在一个带有日期时间字段的非常大的数据库中有一个 Peewee 数据库模型 Products。 当我想选择带有(插入时间大于现在())的文章时,查询将永远挂起。

class Products(BaseModel): 
    id = IntegerField() 
    name= CharField() 
    inserted = DateTimeField() 
 
class Meta: 
    db_table = 'products' 
 
Products.select().where(Products.inserted >datetime(2013, 04, 03, 14, 52, 50).strftime("%Y-%m-%d %H:%M:%S")) 

我不确定是因为数据库大小(大于 10 GB)还是因为查询样式。

我应该像这样使用日期时间 datetime(2013, 04, 03, 14, 52, 50) 还是“2013-04-03 14:52:50”?

请您参考如下方法:

Peewee 将接受 datetime 对象作为输入,因此您无需进行任何转换。我猜问题是您缺少索引。

尝试:

class Products(BaseModel): 
    id = IntegerField(primary_key=True) # <-- You should specify a Primary Key 
    name= CharField() 
    inserted = DateTimeField(index=True) # <-- this should be an index 
 
Products.select().where(Products.inserted >datetime(2013, 04, 03, 14, 52, 50)) 

如果您的表已经存在,您可以使用 python shell 以编程方式添加索引:

# assuming your db is named "db" 
db.create_index(Products, [Products.inserted])