Sampad Mohanty
Sampad Mohanty

Reputation: 131

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.

Upvotes: 9

Views: 13667

Answers (3)

Anto
Anto

Reputation: 610

It is taking the compiled time (the time when the server was started)

[edited] because you have used datetime.datetime.now() (with parenthesis) As suggested by @coleifer you can use datetime.datetime.now (without paranthesis) to initiate a run-time call.

[old answer] Overriding the save method will also work

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

    def save(self, *args, **kwargs):
        self.modified = datetime.datetime.now()
        return super(Something, self).save(*args, **kwargs)

Seems Duplicate of this is there an auto update option for DateTimeField in peewee like TimeStamp in MySQL?

Upvotes: -7

Ashish
Ashish

Reputation: 1

It should be done like this. Override the save method

class myModel(Model):

    name = CharField()
    timestamp = DateTimeField()

    def save(self, *args, **kwargs):
        self.timestamp = datetime.datetime.now()
        super(myModel, self).save(*args, **kwargs)

Works fine after this fix

Upvotes: -3

coleifer
coleifer

Reputation: 26245

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)

Upvotes: 38

Related Questions