【问题标题】:Python orm datetime issuePython orm日期时间问题
【发布时间】:2013-04-03 14:44:53
【问题描述】:

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

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”?

【问题讨论】:

  • 应该没有需要将datetime对象格式化为字符串。 SQLAlchemy 知道如何处理 datetime 对象本身就好了。
  • 如果查询需要很长时间,那么这通常是数据库结构的问题。是否有覆盖inserted 列的索引?
  • 您不需要格式化日期时间——peewee 将处理 python 日期时间对象。我猜你可能需要添加一个索引。

标签: python mysql-python peewee


【解决方案1】:

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

【讨论】:

  • 确实如此,Peewee 没有将列视为索引,因此收集数据需要时间。谢谢!
猜你喜欢
  • 2014-09-04
  • 2020-05-09
  • 2021-12-19
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多