FastAPI Create Users Table / Create Foreign Key - 43

2023. 1. 7. 16:36·Develop/FastAPI
728x90
SMALL
Users 테이블을 만들고 Todos 테이블과의 관계를 설정하는 것이 목표(Foreign key)

1. 라이브러리 import

from sqlalchemy.orm import relationship
from sqlalchemy import ForeignKey

 

2. Users 클래스 생성

class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    username = Column(String, unique=True, index=True)
    first_name = Column(String)
    last_name = Column(String)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)

 

3. 테이블 관계도 설정

class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    username = Column(String, unique=True, index=True)
    first_name = Column(String)
    last_name = Column(String)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
	
    #Todos클래스와 관계형성
    todos = relationship("Todos", back_populates="owner")
    
   ---------------------------------------------------------
   
class Todos(Base):
    __tablename__ = "todos"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    description = Column(String)
    priority = Column(Integer)
    complete = Column(Boolean, default=False)
    #users 테이블의 id의 외래키 생성)
    owner_id = Column(Integer, ForeignKey("users.id"))
	
    #Users 관계형성
    owner = relationship("Users", back_populates="todos")

 

4. DB 접속

터미널에서 sqlite3 todos.db 입력한 후. schema를 입력해서 테이블 확인

CREATE TABLE users (
        id INTEGER NOT NULL, 
        email VARCHAR, 
        username VARCHAR, 
        first_name VARCHAR, 
        last_name VARCHAR, 
        hashed_password VARCHAR, 
        is_active BOOLEAN, 
        PRIMARY KEY (id)
);
CREATE INDEX ix_users_id ON users (id);
CREATE UNIQUE INDEX ix_users_email ON users (email);
CREATE UNIQUE INDEX ix_users_username ON users (username);
CREATE TABLE todos (
        id INTEGER NOT NULL, 
        title VARCHAR, 
        description VARCHAR, 
        priority INTEGER, 
        complete BOOLEAN, 
        owner_id INTEGER, 
        PRIMARY KEY (id),
        #외래키 형성 확인
        FOREIGN KEY(owner_id) REFERENCES users (id)
);
CREATE INDEX ix_todos_id ON todos (id);

 

 

728x90
SMALL
저작자표시 비영리 변경금지 (새창열림)

'Develop > FastAPI' 카테고리의 다른 글

FastAPI bcrypt 비밀번호 암호화 - 45  (0) 2023.01.07
FastAPI Create Authentication & Post Request - 44  (0) 2023.01.07
FastAPI Database Relationship / Foreign Key / Query- 42  (0) 2023.01.07
FastAPI Delete Request를 통한 데이터 삭제 - 41  (0) 2023.01.04
FastAPI Put Request를 통한 DB 업데이트 - 40  (0) 2023.01.04
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI bcrypt 비밀번호 암호화 - 45
  • FastAPI Create Authentication & Post Request - 44
  • FastAPI Database Relationship / Foreign Key / Query- 42
  • FastAPI Delete Request를 통한 데이터 삭제 - 41
동석해요
동석해요
공부하고 싶은게 많은, 사소한 IT 지식들 공유
    250x250
  • 동석해요
    개발로 자기계발
    동석해요
  • 전체
    오늘
    어제
    • 분류 전체보기 (226)
      • Develop (126)
        • 기초지식 (12)
        • FastAPI (102)
        • Django (11)
      • Database & Data (62)
        • 기초지식 (16)
        • MySQL (29)
        • PostgreSQL (8)
        • 데이터 분석 (9)
      • 인공지능 (11)
        • PyTorch (9)
      • Cloud (8)
        • AWS (4)
        • GCP (2)
      • 버그처리 (14)
      • 회고 & 일상 (5)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
동석해요
FastAPI Create Users Table / Create Foreign Key - 43
상단으로

티스토리툴바