Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using datetime.utcnow() to set default value in flask-sqlalchemy [duplicate]

Using the code below, I intend to use the datetime.utcnow() value as the default value for that field, but it gives an Attribute Error message that says 'SQLALchemy' object has no attribute 'Datetime'

from flask import Flask, flash, render_template, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///HRS.sqlite3'
app.config['SECRET_KEY'] = 'any key'

db = SQLAlchemy(app)

class Treatment(db.Model):
    treatmentDate = db.Column('Date of treatment', db.Datetime, default=datetime.utcnow())
like image 512
Stephen C. O. Avatar asked May 03 '26 14:05

Stephen C. O.


1 Answers

In code what the comments already say:

# rest stays the same

class Treatment(db.Model):
    treatmentDate = db.Column('Date of treatment', db.DateTime, default=datetime.utcnow)

"Passing the function and not calling it" means leaving the brackets () at the end off. Calling the function like you do will actually pass in a datetime object, but what you want is to pass in the function itself as the default to be called in the moment you create a new instance of Treatment.

like image 83
mprostock Avatar answered May 05 '26 03:05

mprostock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!