dkmatt0
dkmatt0

Reputation: 243

same default value with python and peewee

I'm going to do a test with PeeWee and I see a big problem. Example :

from uuid import uuid4
import datetime as dt
import time
from peewee import *

dbfile = 'test.db'
db = SqliteDatabase(dbfile)

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

class Example(BaseModel):
    uuid = CharField(default=str(uuid4()))
    date = DateTimeField(default=dt.datetime.now())

try:
    Example.create_table()
except:
    pass
e1 = Example.create()
time.sleep(1)
e2 = Example.create()
print(e1.uuid, e2.uuid) #Same uuid...
print(e1.date, e2.date) #Same date

In this code, uuid and date are the same and it's not normal. Why and how change this to are different value for each new creation ?

Thank you

Upvotes: 1

Views: 1643

Answers (1)

David Jenkins
David Jenkins

Reputation: 471

The problem is in how you are defining the default values for the uuid and date fields. At the time of the Example class definition, in the uuid default declaration you are executing the uuid4 function and assigning that value as the default value. The same is for dt.datetime.now; you are also executing it and assigning the returned time as the default value.

The following change fixes the problem:

class Example(BaseModel):
    uuid = CharField(default=uuid4)
    date = DateTimeField(default=dt.datetime.now)

Upvotes: 5

Related Questions