백엔드 중심으로 서술되었음

위코드 1차 프로젝트 7일차

1. 스탠딩 미팅

  • 백/프론트 상황 공유 : 중간발표 전 자료 공유, 1주차 스프린트 내용 전반적으로 구현 완료되어 감.(80~90%)
  • 오늘 계획 : 상품상세 정보 등록 및 출력 풀리퀘스트 + 장바구니, 위시리스트, 주문 시작

2. 상품 상세 정보 피드백

  1. 상품 상세 정보 등록
  • import로 부르는 값이 길어질 경우 2~3개 씩 그룹지어 구분하기
  • 트렌젝션 이용하기

    간단히 이해하면 1 2 3 4 작업 중에 3에서 막혔으면 1로 롤백 해줘서 에러 안나고 손실 안 나게 해주는 것.

  • get_or_create를 활용한 튜플 언패킹

    있으면 get, 없으면 create 해주는 기능. 디폴트 값을 지정할 수 있다.

  1. 상품 상세 정보 출력
  • 만일 url에서 /product/1 이런 식으로 받으려면 아래와 같이 해주면 됨
re_path(r'^/(?P<product_id>\d+)$', ProductView.as_view()),

정규표현식까지 보다는

    path('/<int:product_id>', ProductView.as_view()),
  • 리턴 데이터 타입 : product.price가 decimal 타입인데 프론트엔드에서 받을 때 "5500.55"로 string처리 됨. 이를 float 처리해줘서 숫자로 바꿔주기

  • 돈 단위는 int로 받기 보다는 decimal로.(유로, 달러)

  • 리스트 컴프리헨션 공부하기 : 리스트, 딕셔너리 안에서 리스트, 딕셔너리를 돌려서 만들기.

    이것도 추가로 공부 더 해주기

>>> id_name = {1: '박진수', 2: '강만진', 3: '홍수정'}
>>> name_id = {val:key for key,val in id_name.items()}
>>> name_id
{'박진수': 1, '강만진': 2, '홍수정': 3}
>>> dictionary = {'a':1, 'b':2, 'c':3}
>>> dicc = {k:v for v,k in dictionary.items()}
>>> dicc
{1: 'a', 2: 'b', 3: 'c'}

이를 views.py에 추가해줘야 하는 것 필요

  • dict와 {} 중 속도, 메모리 면에서 {}가 더 유리
>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
  • product/views.py conflict 수정
    -> 수정 과정 중 뷰 분리(post, get)

3. 모델링 최종 결과 :

  • 고민 사항 : 위시리스트, 장바구니에서 옵션값이 있을지 없을지 유무에 따라 상황이 변경
  • 해결 : product_option을 연결

4. 오늘 한 일 : 위시리스트 만들기

  1. 고민한 것 :
  • 어떤 데이터가 만들어지고 뿌려져야 하는가?
  • 그렇게 하기 위해서는 데이터를 어떻게 가져와야 하는가?
  • 도움 받은 것 : 시작하기. 방향성. (어떤 값들이 들어와야 하는지, 뭐가 필요 없는지, 어떤 인스턴스가 만들어질 필요가 없는지)
  • 고민 끝에 만든 코드
import json
from json import JSONDecodeError

from django.views import View
from django.http  import JsonResponse

from .models        import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models    import User

class WishListView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            
            user = User.objects.get(username=data['username'])
            # user는 아이디로 가져옴
            
            wishlist = WishList.objects.create(
                quantity          = data['quantity'],
                product_id        = data['product_id'],
                user              = user,
                product_option_id = data['product_option_id']
            )
            # 들어가야 할 4가지 자료, 모두 프론트가 입력해준다는 생각으로
            return JsonResponse({'message' : 'SUCCESS'}, status=200)
        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
        except WishList.DoesNotExist:
            return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)    

    
    def get(self, request):
        wishlists = WishList.objects.filter(user_id=3)
        # 아직 데이터 데코레이터 안해서 3번 아이디를 기준
        result = list()
        try:
            for wishlist in wishlists:
                my_dict = dict(
                    quantity          = wishlist.quantity,
                    product_id        = wishlist.product.id,
                    user_id           = wishlist.user.id,
                    product_option_id = wishlist.product_option.id
                )
                result.append(my_dict)
            return JsonResponse({'result' : result}, status=200)
        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
        except WishList.DoesNotExist:
            return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)
            
            # 최대한 많은 예외처리
  1. 포스트맨으로 맞춰보기

  1. 프론트엔드와 맞춰보기 전 수정

    단순히 아이디만 보내주는 것이 아니라 받을 때는 아이디를 받되 보낼 때는 명을 보내주는것(point, 가격 포함)

import json
from json import JSONDecodeError

from django.views import View
from django.http  import JsonResponse
from django.db    import transaction

from .models        import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models    import User

class WishListView(View):
    @transaction.atomic
    def post(self, request):
        try:
            data = json.loads(request.body)
            
            user = User.objects.get(username=data['username'])
            
            wishlist = WishList.objects.create(
                quantity          = data['quantity'],
                product_id        = data['product_id'],
                user              = user,
                product_option_id = data['product_option_id']
            )
            return JsonResponse({'message' : 'SUCCESS'}, status=200)
        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
        except WishList.DoesNotExist:
            return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)    

    
    def get(self, request):
        wishlists = WishList.objects.filter(user_id=3)
        result = list()
        try:
            for wishlist in wishlists:
                product = wishlist.product
                user    = wishlist.user
                # product 직접 접근 가능
                my_dict = dict(
                    quantity          = wishlist.quantity,
                    product_id        = product.id,
                    product           = product.name,
                    product_thumnail  = product.thumbnail_image_url,
                    user_id           = wishlist.user.id,
                    product_option_id = wishlist.product_option.id,
                    price             = product.price,
                    point             = user.point
                )
                result.append(my_dict)
            return JsonResponse({'result' : result}, status=200)
        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
        except WishList.DoesNotExist:
            return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)

  1. 프론트엔드와 통신 결과
  • 이후 가격까지 이상없이 보내짐

<최종 프론트엔드 통신 현황>


  1. 트랜젝션 추가
from django.views import View
from django.http  import JsonResponse
from django.db    import transaction

from .models        import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models    import User

class WishListView(View):
    @transaction.atomic
    def post(self, request):
  • 팀원 : 장바구니 제작 완료

5. git 관련 확인 사항

내 팀원 PR이 리뷰를 거친 후 최종 머지가 되었을때 내가 작업하던 브랜치에 해당 내용을 병합할때 스텝

  • master이동 - git pull origin master - 내 브랜치 이동 - git merge master

6. 내일 할 일

  • 데코레이터
  • 위시리스트(찜하기) 마무리
  • 장바구니 마무리
  • 카테고리별 상품 뿌려주기 마무리(PR)
  • (추가) 결제하기
profile
커피 내리고 향 맡는거 좋아해요. 이것 저것 공부합니다.

0개의 댓글