Skip to content

Commit a0c1b96

Browse files
committed
2 parents dc2147d + fee739f commit a0c1b96

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

app/handlers/product_handler.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,4 +332,32 @@ def get_product_purchase_info(
332332
"purchased": True,
333333
"buyer_id": purchase.user_id,
334334
"purchase_date": purchase.purchase_date
335-
}
335+
}
336+
337+
def increment_view_count(db: Session, product_id: int):
338+
# 상품 존재 여부 확인
339+
product = db.exec(select(Product).where(Product.id == product_id)).first() # ✅ select() 사용
340+
if not product:
341+
return None # 존재하지 않는 상품
342+
343+
# 조회수 확인 후 증가
344+
product_view = db.exec(select(ProductView).where(ProductView.product_id == product_id)).first() # ✅ select() 사용
345+
346+
if not product_view:
347+
product_view = ProductView(product_id=product_id, product_views=1)
348+
db.add(product_view)
349+
else:
350+
product_view.product_views += 1
351+
352+
db.commit()
353+
db.refresh(product_view) # ✅ 세션에서 새로고침
354+
return product_view
355+
356+
@router.post("/{product_id}/view")
357+
def increment_view(product_id: int, db: Session = Depends(get_db_session)):
358+
product_view = increment_view_count(db=db, product_id=product_id)
359+
print(product_view)
360+
if not product_view:
361+
raise HTTPException(status_code=404, detail="Product not found")
362+
363+
return {"product_id": product_id, "views": product_view.product_views}

app/models/user_and_product_model.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,8 @@ class ProductSortType(Enum):
106106

107107

108108
class RespComments(BaseModel):
109-
comments : list[Comment]
109+
comments : list[Comment]
110+
111+
class ProductView(SQLModel, table=True): # ✅ 테이블로 지정
112+
product_id: Optional[int] = Field(default=None, foreign_key="product.id", primary_key=True) # ✅ default=None 추가
113+
product_views: int = Field(default=0) # ✅ 기본값 추가

carrot.db

4 KB
Binary file not shown.

0 commit comments

Comments
 (0)