( 춤 안춥니다. )
이번 시리즈는...
잇츠 어메이징! 쏘 뷰티풀 코드!
우리 코드가 달라졌어요.
입니다.
(우와아아아앙아ㅏㅏㅏㅏ~!!!!)
Django 프로젝트에서 GET 요청을 받아 필터링 기능을 구현해야하는 상황쓰!
filter_dict = {}
if request.GET.getlist('gender', None):
filter_dict['gender__in'] = request.GET.getlist('gender', None)+['남녀공용','유니섹스']
if request.GET.getlist('color', None):
filter_dict['product_color__color_code__in'] = request.GET.getlist('color', None)
if request.GET.getlist('size', None):
filter_dict['product_size__size__in'] = request.GET.getlist('size', None)
if request.GET.getlist('silhouette', None):
filter_dict['silhouette_id__name__in'] = request.GET.getlist('silhouette', None)
product_list = [product for product in products.filter(**filter_dict).values('id','code','name','price')]
product_list = [
product for product in products.filter(
**{
(
key + '__in' if key == 'gender' else
'product_' + key + '__' + key + '_code__in' if key == 'color' else
'product_' + key + '__' + key + '__in' if key == 'size' else
key + '_id__name__in'
) : (
request.GET.getlist(key) + ['남녀공용', '유니섹스']
if key == 'gender' else
request.GET.getlist(key)
)
for key in request.GET
if key in ['gender','color','size','silhouette']
}
).values('id','code','name','price')]
만약에 조건부로 필터링을 거는 기능을 구현해야하는 상황이 오신다면,
위의 개선된 코드를 분석해보시고, 본인의 상황에 맞게 사용하시면 좋을 것 같아요 ㅎ
고생하셨습니다.
' 코드가 더 짧아져야 개선된 것 아니냐! ' 고 생각하시는 분들께!
저거 사실 한줄짜리 코드인데, 가독성 때문에 좀 나눠놓은거에요 ㅋㅋㅋ