'Postgresql sqlalchemy default time now() giving same time over and over again
I have field inside table that is time
time = db.Column(db.Time, default=datetime.datetime.now().time(), nullable=False)
and for some reason it keeps defaulting on same time instead of actual system time
"23:53:27.34808"
"20:10:29.613031"
"20:10:29.65371"
"20:10:29.230696"
"20:10:29.613031"
"01:40:41.962449"
"20:10:29.375499"
"09:48:38.981206"
"10:42:38.56931"
"10:42:38.56931"
"10:42:38.56931"
"10:42:38.541895"
"10:42:38.56931"
"10:42:38.56931"
"10:42:38.56931"
"05:01:44.076726"
"10:42:38.56931"
"15:15:18.271026"
"07:29:20.49368"
"15:15:18.271026"
"15:15:18.271026"
if you look at times there are 4 or 5 same times and it supposed to take time right now as default option
any ideas to what might be causing it?
Solution 1:[1]
default=datetime.datetime.now().time() will be evaluated once, at import time, leading to the observed behaviour of all instances being assigned the same value.
The usual solution when providing a Python function as a default is to provide the function object:
default=func, ....
but in this case, two function calls are involved (.now() and .time()), so the solution is to define a function (or a lambda) that performs both:
def default_time():
return datetime.datetime.now().time()
...
time = db.Column(db.Time, default=default_time, nullable=False)
Using this approach, default_time will be called each time it's required, and a new value returned for each instance.
See also the SQLAlchemy docs on using Python functions as defaults.
As user Belayer implies in the comments, it's common to delegate generating timestamps to the database rather than generating them in Python. In that case you would set the server_default attribute on the column, for example like this:
time = db.Column(db.Time, server_default=sqlalchemy.text('NOW()'))
or
time = db.Column(db.Time, server_default=sqlalchemy.func.now())
There are various functions on the database side that will generate timestamps, and they are often specific to the particular database engine so you may need to research to find the function that best suits your needs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
