TypeError: column() got an unexpected keyword argument 'default'

Question:

I am making a website with Flask and am using SQLAlchemy for my database. And I encountered the problem when creating an column in my database. Error is: TypeError: column() got an unexpected keyword argument 'default'
This is where the problem is: date = db.column(db.DateTime(timezone=True), default=func.now())

My code:

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    notes = db.relationship('Note')

I don’t know why this doesn’t work so I uninstalled Flask and installed it back again, but it didn’t help.

Asked By: Rok Kužner

||

Answers:

Try the approach mentioned here SQLAlchemy default DateTime

from sqlalchemy.sql import func

time_created = Column(DateTime(timezone=True), server_default=func.now())
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
Answered By: Sushant Agarwal

In SQLAlchemy, column and Column are two different things and not interchangeable.

column is used to create ColumnClauses, used usually for TextualSelects and such, consider it a disposable column indicator.

Column is used the create mapped columns.

You use db.column which should be db.Column, python is case sensitive.

Also func.now() is a server side function, so you should set it default as a server_default.

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), server_default=func.now())  # NOTE: capital C
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
Answered By: ljmc
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.