'Create table with rows using SQLAlchemy?
I want to create tables containing rows once, when the database is created. Is there a 'native' way how to do this rather than having to use the session and check if the rows exist before adding them?
This is sample code I'm using..
/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from ..const import (
DATABASE_URL
)
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
/dataset/menu/model.py
from sqlalchemy import Column, Integer, String, exc
from ...database import Base, SessionLocal
class Menu(Base):
__tablename__ = "menus"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
title = Column(String)
icon = Column(String)
/main.py
from .database import database
database.Base.metadata.create_all(bind=database.engine)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
