SQLAlchemy User and Post Models with In-Memory SQLite Database

  • Share this:

Code introduction


This code defines two SQLAlchemy models: User and Post, and connects them using relationships. It also creates an in-memory SQLite database and a session.


Technology Stack : SQLAlchemy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

def create_user_table():
    Base = declarative_base()
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String)
        age = Column(Integer)
        posts = relationship("Post", back_populates="author")
    
    class Post(Base):
        __tablename__ = 'posts'
        id = Column(Integer, primary_key=True)
        title = Column(String)
        content = Column(String)
        author_id = Column(Integer, ForeignKey('users.id'))
        author = relationship("User", back_populates="posts")
    
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    return session                
              
Tags: