python
Create table model using SQLAlchemy
Using SQLAlchemy you can create tables by defining the class schema and then upgrading your database.
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String
from datetime import datetime
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String, nullable=False)
firstname = Column(String)
lastname = Column(String, nullable=True, default='')
created_date = db.Column(db.DateTime, default=datetime.now())
def __repr__(self):
return "<User(username='%s', firstname='%s', lastname='%s')>" % (self.username, self.firstname, self.lastname)
In the code snippet, we are creating a table named users and adding columns to it with names - username, firstname, lastnamee, created_date. We can also enable check on columns whether it can be null or not by using nullable and assigning True or False to it. You can also assign a default value to it means if the column does not have a value at the time of insertion then it will be filled with the deafult value.
Was this helpful?
Similar Posts