Python&Django 코드 리뷰 #2

dev-swd·2020년 11월 29일
1

코드리뷰

목록 보기
2/2

코드 리뷰 수정 1

if not type(product_id) is int:
# 이 역할을 하는 파이썬의 함수가 있다. 해당 함수를 써보도록..!
 
# 수정 후
if isinstance(product_id, int):

# isdemical 은 str 이 가지고 있는 메서드.
path parameter 로 int 형태로 받았기 때문에 isinstance 를 사용했다.

코드 리뷰 수정 2

product = Product.objects.get(id=product_id)
product_detail_images = product.productdetailimage_set.filter(product=product)

# 이미 product 객체를 지칭했기 때문에, 이 객체의 productdetailimage_set 은 모두 해당 product 의 객체이다. 따라서 product 로 다시 filtering 을 해줄 필요가 없다.

# 수정 후
product = Product.objects.get(id=product_id)
product_detail_images = product.productdetailimage_set.all()

코드 리뷰 수정 3

detail_images = []
if product_detail_images:
    detail_images = [images.detail_image_url for images in product_detail_images]

# 리스트 컴프리헨션은 선언 하는 그 자체만으로도 리스트를 생성해준다. 따라서 빈 리스트를 만들어 줄 필요가 없다.

# 수정 후
detail_images = [images.detail_image_url for images in product_detail_images]

코드 리뷰 수정 4

review_points_avg = 0
if reviews:
    total_review_point = 0
    for review in reviews:
        total_review_point += review.star

# 특정 해 온 리뷰들의 평점을 구하는 로직이다. 장고에서 제공해주는 메서드가 있다.

# 수정 후
avg_reviews_point = reviews.aggregate(Sum('star')).get('star__sum') / reviews.count()

# 다시 한 번 수정 (리스트 표현식이 더 빠르다는 글을 보고 수정)
avg_reviews_point = round(sum([review.star for review in reviews]) / reviews.count())

#참고 링크: https://stackoverflow.com/questions/8616343/django-calculate-the-sum-of-the-column-values-through-query


if product:

# 위에서 get 으로 product 를 뽑아온 상황에서, 객체가 없다면 Product.DoesNotExist 에러 헨들링으로 잡아주고 있기 때문에, if product는 언제나 참이 된다. 따라서 가정해주지 않아도 된다.
profile
개발을 취미로 할 수 있는 그 때 까지

1개의 댓글

comment-user-thumbnail
2020년 11월 29일

좋은 정보.. 사륜안 ON 코드카피닌자

답글 달기