본문 바로가기
ERROR

GenericView perform_create에서 에러 발생시키기

by 코드뭉치 2023. 6. 26.

리뷰를 이미 작성한 유저이거나, 상품을 구매하지 않은 유저는 리뷰를 작성할 수 없도록 하는 코드 작성 중,

    def perform_create(self, serializer):
        product = get_object_or_404(Product, id=self.kwargs.get("product_id"))
        user = self.request.user
        has_bought = OrderItem.objects.filter(bill__user=user, product_id=product.id).exists()
        has_reviewed = Review.objects.filter(user=user, product=product).exists()

        print(has_reviewed, has_bought)
        if has_reviewed:
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
	...


perform_create에서 return Response를 통해 http statuscode를 보내주고 있었음. 

그러나 perform_create는 리턴값을 반환하지 않는 메소드이기 때문에,

반환한다고 해도 다음 함수를 실행하는 과정에서 아무런 일도 일어나지 않았음.

 

if has_reviewed:
    raise NotAcceptable(detail="이미 리뷰한 상품입니다")
if not has_bought:
    raise ValidationError(detail="구매이력이 없습니다")


Error를 raise하도록 수정해서 해결.

댓글