Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Peewee I have a datetime field defaulted to datetime.datetime.now(). But when inserted, it takes the time the server was started. Why

When I insert a row, the field is filled with the time when the server was started not the time when the row was inserted. Why is this happening and what is the solution? BTW I am using SQLite.

class LOG(peewee.Model):
    id = peewee.IntegerField(unique=True,primary_key=True)
    timestamp = peewee.DateTimeField(default=datetime.datetime.now())
    log = peewee.CharField()
    by = peewee.IntegerField(default=1)
    class Meta:
        database = database


  LOG.create(log = _log , by = _by)  
  # above statement is called at say 3:00 pm and I started the server at 2:00 pm, then the row is inserted with timestamp of 2pm not 3pm.
like image 454
Sampad Mohanty Avatar asked Oct 07 '15 10:10

Sampad Mohanty


1 Answers

When your field is loaded by the Python interpreter, it calls datetime.datetime.now() once and only once. So you will always get the same value.

Peewee supports using callables for default args, so rather than calling now() just pass in the function:

timestamp = peewee.DateTimeField(default=datetime.datetime.now)
like image 50
coleifer Avatar answered Sep 27 '22 17:09

coleifer