[], {}
가 속도 더 빠름class WishListView(View):
@auth_check
# 토큰
@transaction.atomic
def post(self, request):
try:
results = json.loads(request.body)['results']
딕셔너리 형태로 가져온 프론트에서 받은 내용
user_id = request.user.id
# 토큰 까기
for result in results:
product_id = result['product_id']
quantity = result['quantity']
product_option_id = result['product_option_id']
product_option_quantity = result['product_option_quantity']
# for loop으로 딕셔너리 내용 까기
{"results": [
{"product_id": 1,
"quantity" :4,
"product_option_id": "",
"product_option_quantity":0
}]
}
토큰을 깠을 때 나오는 정보가 유저의 정보(보통 id)가 무엇인지 이해해야 한다.
토큰을 가져오는 데코레이터의 구조를 이해한다.
우리 조는 결과가 result라는 딕셔너리 형태로 온다. 따라서 이를 바디에서 가져오는 방식을 이해해야 한다.(대괄호)
이를 for 문을 돌려서 한 번 풀어준다. 그리고 푼 정보(프론트가 전달해준 정보)를 result와 연동하여 정리한다.
우리조의 경우 옵션이 있는 경우와 없는 경우를 if문으로 나눠서 관리했다.
if product_option_id:
# 만일 product_option_id가 있으면
wishlist, is_created =
# 언패킹
WishList.objects.get_or_create(
product_id = product_id,
product_option_id = product_option_id,
user_id = user_id,
defaults = {'quantity': product_option_quantity}
# get_or_create 문법
옵션이 있다고만 가정한 것을 보고 위에서 정의해준 내용을 바탕으로 create해주면 된다.
만일 컬럼 한 줄을 다 채우는 식을 하나 썼다 치자. 그리고 이를 양말이라 치자. 근데 만일 같은 사람이 같은 양말을 같은 옵션으로 다른 갯수로 다시 위시리스트에 담았다. 그러면 컬럼이 또 생기는게 좋을까 아님 갯수만 올라가는게 좋을까? 당연히 후자다. 이 때 갯수를 디폴트로 놓고 나머지 값들로 이 컬럼을 판단하는 과정이 get_or_create다.
unique_together는? 이미 그 관계가 모델링되어 있다. 따라서 이 모델링에 맞춰서 디폴트 값이 갯수가 되어야 한다는 것이다.
class Meta:
db_table = 'wishlist'
unique_together = ('product', 'user', 'product_option')
if not is_created:
# False
wishlist.quantity += product_option_quantity
wishlist.save()
@auth_check
def get(self, request):
wishlists = WishList.objects.filter(user_id=request.user.id)
# 토큰 통한 하드코딩 방지
try:
results = [{
'point' : wishlist.user.point,
'quantity' : wishlist.quantity,
'user_id' : wishlist.user.id,
'product_option_id' : wishlist.product_option.id,
'product_id' : wishlist.product_id,
'product_name' : wishlist.product.name,
'product_thumnail' : wishlist.product.thumbnail_image_url,
'product_price' : wishlist.product.price if not wishlist.product_option\
else wishlist.product.price + wishlist.product_option.additional_price ,
'total_price' : wishlist.quantity * wishlist.product.price if not wishlist.product_option\
else wishlist.quantity * (wishlist.product.price + wishlist.product_option.additional_price),
'product_option_classification': wishlist.product_option.option.classification,
'product_option_name' : wishlist.product_option.option.name
} for wishlist in wishlists]
return JsonResponse({'result' : results}, status=200)
>>> [x for x in range(1, 10+1) if x % 2 == 0]
[2, 4, 6, 8, 10]
-> 무조건 적으로 for loop을 쓰지 말란게 아니라 리스트 컴프리핸션이 되거나, 불필요한 변수를 for 로 가져오는 것을 지양하라는 것. 여기서는 위의 로직대로라면 한 개의 상품만 위시리스트에 담을 수 있으므로 상품을 다 가져와서 for loop처리 해주는 것이 좋다.
정참조, 역참조 및 json으로 데이터 출력에 대한 이해가 부족하여 과제가 부여되었고 두 문제가 출제 되었다. 하나는 정참조를 할 수 있는지, 하나는 역참조가 무엇인지 아는지였다.
{
"results":[
{
"name":"웅이",
"breed":"푸들",
"age":7,
"owner":"손승현"
},
{
"name":"짱아",
"breed":"페키니즈",
"age":3,
"owner":"손승현"
},
{
"name":"삐삐",
"breed":"요크셔테리어",
"age":8,
"owner":"박지훈"
},
{
"name":"버블",
"breed":"푸들",
"age":2,
"owner":"강경훈"
},
{
"name":"왕자",
"breed":"진돗개",
"age":1,
"owner":"김순태"
}
]
}
[
{
"name":"손승현",
"email":"jamessoun93@gmail.com",
"age":17,
"dogs":[
{
"name":"웅이",
"breed":"푸들",
"age":7
},
{
"name":"짱아",
"breed":"페키니즈",
"age":3
}
]
},
{
"name":"박지훈",
"email":"ulfrid@gmail.com",
"age":19,
"dogs":[
{
"name":"삐삐",
"breed":"요크셔테리어",
"age":8
}
]
},
{
"name":"강경훈",
"email":"kyunghun@gmail.com",
"age":18,
"dogs":[
{
"name":"버블",
"breed":"푸들",
"age":2
}
]
},
{
"name":"김순태",
"email":"kst@gmail.com",
"age":17,
"dogs":[
{
"name":"왕자",
"breed":"진돗개",
"age":1
}
]
}
이건 내가 하는 프로젝트 product와 product_image 예시
In [51]: p8.productimage_set.all()
Out[51]: <QuerySet [<ProductImage: ProductImage object (1)>]>
In [52]: p8.productimage_set.all().first()
Out[52]: <ProductImage: ProductImage object (1)>
In [53]: p8.productimage_set.all().first().image_url
Out[53]: 'https://endlessfight1.openhost.cafe24.com/web/product/2018/haguesock.jpg'
get(불러오기)
post(항목 같으면 갯수만 올라가게)
프론트와 맞춘 결과
class CouponView(View):
def post(self, request):
try:
data = json.loads(request.body)
name = data['name']
discount_price = data['discount_price']
issue_date = data['issue_date']
expire_date = data['expire_date']
coupons = Coupon.objects.create(
name = name,
discount_price = discount_price,
issue_date = issue_date,
expire_date = expire_date
)
return JsonResponse({'message' : 'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
로그인이나 회원가입 참고하여 간단히 만듦.
def post(self, request):
# 데이터 집어 넣는 것이니 post
try:
data = json.loads(request.body)
coupon = Coupon.objects.get(id=data['coupon_id']).id
user = User.objects.get(id=data['user_id']).id
quantity = data['quantity']
# 각 아이디 및 수량 받아 옴.
user_coupon, is_created = UserCoupon.objects.get_or_create(
coupon_id = coupon,
user_id = user,
defaults = {'quantity' : quantity}
)
if not is_created:
user_coupon.quantity += data['quantity']
user_coupon.save()
# 마찬가지로 같은 쿠폰을 받을 경우 수량을 늘려야 함.
return JsonResponse({'message' : 'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
이후 구현해야할 사항 : 유저와의 관계 보강(단순히 관계만 맺음 / 서브 카테고리와의 관계
유저에게 무료 금액 쿠폰을 가입할 때 부여하는 방식 및 서브 카테고리마다 쿠폰이 존재하는 로직이 필요.