Search code examples
postgresqlpeeweeflask-peewee

Peewee Python Default is not reflecting in DateTimeField


Not able to set default timestamp in spite of using DateTimeField(default=datetime.datetime.now) The column is set to not null but no default value is set

I have my model

import datetime

database = PostgresqlDatabase(dbname,username,password,host)

class BaseModel(Model):
    class Meta:
        database = database

class UserInfo(BaseModel):
     id = PrimaryKeyField()
     username = CharField(unique=True)
     password = CharField()
     email = CharField(null=True)
     created_date = DateTimeField(default=datetime.datetime.now)

when I create table using this model and below code

 database.connect()
 database.create_tables([UserInfo])

I am getting below table

                                  Table "public.userinfo"
Column        |            Type             |                       Modifiers                       
--------------+-----------------------------+-------------------------    ------------------------------
 id           | integer                     | not null default    nextval('userinfo_id_seq'::regclass)
 username     | character varying(255)      | not null
 password     | character varying(255)      | not null
 email        | character varying(255)      | 
 created_date | timestamp without time zone | not null
Indexes:
    "userinfo_pkey" PRIMARY KEY, btree (id)
    "userinfo_username" UNIQUE, btree (username)

Here in table created date doesn't set to any default


Solution

  • When using the default parameter, the values are set by Peewee rather than being a part of the actual table and column definition

    try created_date = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])