Search code examples
pythonmysql-pythonpeewee

Python orm datetime issue


I have a Peewee database model Products in a very big database with a datetime field. when i want to select articles with (inserted time bigger than now()) the query hangs forever.

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

I'm not sure if it's because of the database size (bigger than 10 GB) or it's because of the query style.

Should i use datetime like this datetime(2013, 04, 03, 14, 52, 50) or "2013-04-03 14:52:50" ?


Solution

  • Peewee will accept datetime objects as input, so you do not need to do any conversion. I would guess the problem is you are missing an index.

    Try:

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

    If your table already exists, you can add an index programmatically using the python shell:

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