models
"/home/yossef/notes/full-stack/python-backend/fastapi/curd_sql/models.md"
path: full-stack/python-backend/fastapi/curd_sql/models.md
- **fileName**: models
- **Created on**: 2025-04-15 17:19:01
this file for creating the table structure in database
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from .database import Base # import base from database
# what base real mean it's using this class to inherit from it on others
# class because when starting the project gone create a table based on the
# class that inherit from base class
# models.Base.metadata.create_all(bind=engine)
# this create tables in db based on Base Class
class User(Base):
__tablename__ = "users"
# index = True, tell sqlalchemy make sure that the column id
## to be created !!important
id = Column(Integer, primary_key=True, index=True)
email = Column(String(255), index=True, unique=True)
hash_password = Column(String(255))
is_active = Column(Boolean, default=True)
## tell sqlalchmey to make a relation between User and Item
## and look for the column owner in Item table
items = relationship("Item", back_populates="owner")
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), index=True)
description = Column(String(255), index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
## look for the column items in User table
owner = relationship("User", back_populates="items")
continue:./curd.md
before:./database.md