개발로 자기계발
article thumbnail
728x90
Alembic이 아닌 코드 자체에서 Foreign key 설정

 

1. models.py 수정

from sqlalchemy import Boolean, Column, Integer, String, ForeignKey
from database import Base
from sqlalchemy.orm import relationship


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)
    phone_number = Column(String)
    # foreignkey 생성
    address_id = Column(Integer, ForeignKey("address.id"), nullable=True)

    todos = relationship("Todos", back_populates="owner")
    
    #Address 클래스와 관계 생성
    address = relationship("Address", back_populates="user_address")


class Address(Base):
    __tablename__ = "address"

    id = Column(Integer, primary_key=True, index=True)
    address1 = Column(String)
    address2 = Column(String)
    city = Column(String)
    state = Column(String)
    country = Column(String)
    postalcode = Column(String)

    user_address = relationship('Users', back_populates="address")

 

2. router 디렉터리에 address.py 생성

import sys
sys.path.append("..")

from typing import Optional
from fastapi import Depends, APIRouter
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
from pydantic import BaseModel
from .auth import get_current_user, get_user_exception


router = APIRouter(
    prefix="/address",
    tags=["address"],
    responses={404: {"description":"Not found"}}
)

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

def successful_response(status_code:int):
    return {
        'status': status_code,
        'transaction': 'Successful'
    }

class Address(BaseModel):
    address1: str
    address2: Optional[str]
    city: str
    state: str
    country: str
    postalcode: str

 

3. address.py에 POST API 생성

@router.post("/")
async def create_address(address: Address,
                         user: dict = Depends(get_current_user),
                         db: Session = Depends(get_db)):
    if user is None:
        raise get_user_exception()

    # address 테이블 데이터 생성
    address_model = models.Address()
    address_model.address1 = address.address1
    address_model.address2 = address.address2
    address_model.city = address.city
    address_model.state = address.state
    address_model.country = address.country
    address_model.postalcode = address.postalcode

    db.add(address_model)
    db.flush()

    # user 테이블 데이터 업데이트
    user_model = db.query(models.Users).filter(models.Users.id == user.get("id")).first()
    user_model.address_id = address_model.id

    db.add(user_model)

    db.commit()
    
    return successful_response(200)

 

4. main.py에 router 등록

app.include_router(address.router)

 

5. user token 발행 후 postman 접속

seok 사용자 toekn 발행 

 

6. address 데이터 생성(PostgreSQL 확인)

데이터를 만들고 삭제했기때문에 id가 4인 상태
address_id에 address table id인 4값이 들어간것을 볼 수 있다.

 

728x90
SMALL
profile

개발로 자기계발

@김잠봉

틀린부분이나 조언이 있다면 언제든 환영입니다:-)