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

Sampad Mohanty picture Sampad Mohanty · Oct 7, 2015 · Viewed 7.6k times · Source

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.

Answer

coleifer picture coleifer · Oct 24, 2015

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)