DateTime Column is not coded properly
John-Male opened this issue · 3 comments
Hi
This page has the following code for the ORM
https://www.pythonsheets.com/notes/python-sqlalchemy.html
class TestTable(Base): __tablename__ = 'Test Table' id = Column(Integer, primary_key=True) key = Column(String, nullable=False) val = Column(String) date = Column(DateTime, default=datetime.utcnow)
The proper way to code the DateTime column is
class TestTable(Base): __tablename__ = 'Test Table' id = Column(Integer, primary_key=True) key = Column(String, nullable=False) val = Column(String) date = Column(DateTime(), default=datetime.utcnow)
If you use the code from your example and have two DateTime columns coded this way then SQLalchemy will raise this error on the second column. sqlalchemy.exc.ArgumentError: Column must be constructed with a non-blank name or assign a non-blank .name before adding to a Table.
Could you provide an example for me?
I try this
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
engine = create_engine('sqlite://')
Base = declarative_base()
class TestTable(Base):
__tablename__ = 'Test Table'
id = Column(Integer, primary_key=True)
key = Column(String, nullable=False)
val = Column(String)
ctime = Column(DateTime, default=datetime.utcnow)
mtime = Column(DateTime)
# create tables
Base.metadata.create_all(bind=engine)
# create session
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
data = {'a': 5566, 'b': 9527, 'c': 183}
try:
for _key, _val in data.items():
row = TestTable(key=_key, val=_val)
session.add(row)
session.commit()
except SQLAlchemyError as e:
print(e)
finally:
session.close()
but there is no sqlalchemy.exc.ArgumentError.
Oh! it seems like you encountered a name conflict issue. I think that using DateTime
class TestTable(Base):
__tablename__ = 'Test Table'
id = Column(Integer, primary_key=True)
key = Column(String, nullable=False)
val = Column(String)
ctime = Column(DateTime, default=datetime.utcnow)
is fine because name conflict should be handled by programmers. However, you remind me that DateTime(timezone=True)
would be useful if datetime columns are timezone sensitive. Thanks!