peewee field default type and DateTimeField

Question:

I have created model class inherititng form peewee.Model

import peewee

class Example(peewee.Model):
    id = peewee.IntField(primary_key=True)
    text = peewee.charField(default="waiting")
    dt = peewee.DateTimeField(default=datetime.datetime.now().strftime('%Y-%m-%d'))

but when I insert new value for just only id field to the example table I do not get the default text value as “waiting” and date_added also comes out to be 0000-00-00 00:00:00 isntead of current date time.

Asked By: Ciasto piekarz

||

Answers:

The fields need to be members of the class:

class Example(peewee.Model):
    id = peewee.IntField(primary_key=True)
    text = peewee.CharField(default="waiting")
    dt = peewee.DateTimeField(default=datetime.datetime.now)

Additionally, you want the default value to be a callable for the datetime…otherwise it will evaluate datetime.datetime.now() at the time the module is loaded and never re-evaluate it.

Answered By: coleifer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.