개발로 자기계발
article thumbnail
728x90
사용자를 등록할 때 전화번호를 필수 열로 만든다.
apt_num의 열을 생성한다.
model에 apt_num열을 Optional로 생성한다.

 

1. auth.py 수정

#phone_number 열 추가
class CreateUser(BaseModel):
    username: str
    email: Optional[str]
    first_name: str
    last_name: str
    password: str
    phone_number: Optional[str]
    
#phone_number 열 추가
@router.post("/create/user")
async def create_new_user(create_user: CreateUser, db: Session = Depends(get_db)):
    create_user_model = models.Users()
    create_user_model.email = create_user.email
    create_user_model.username = create_user.username
    create_user_model.first_name = create_user.first_name
    create_user_model.last_name = create_user.last_name
    create_user_model.phone_number = create_user.phone_number

    hash_password = get_password_hash(create_user.password)

    create_user_model.hashed_password = hash_password
    create_user_model.is_active = True

    db.add(create_user_model)
    #db.flush()
    db.commit()

 

2. Swagger로 데이터 생성

 

3. Alembic으로 새 버전 생성

 

4. Alembic으로 테이블 열 생성

 

5. models.py 수정

#apt_num열 추가
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)
    apt_num = Column(Integer)

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

 

6. address.py 수정

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


@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
    #apt_num 추가
    address_model.apt_num = address.apt_num

    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)

 

7. Postman으로 address 데이터 생성

 

728x90
SMALL
profile

개발로 자기계발

@김잠봉

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