본문으로 바로가기

장고 ORM 에서 get 과 filter 차이

category 장고 2019. 2. 7. 14:24

# get 과 filter 의 차이



Model.objects.filter


- filter 의 경우, cart_item 에 쿼리셋을 반환해서 가지고 있기 때문에 필히 for 문을 순회하며 각각의 필드에 접근해야 한다.

def remove_cart(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    cart = Cart.objects.get(cart_id=_cart_id(request))
    cart_item = CartItem.objects.filter(product=product, cart=cart)
    for cart_item in cart_items:
        if cart_item.quantity > 1:
            cart_item.quantity -= 1
            cart_item.save()
        else:
            cart_item.delete()
    return redirect('cart:cart_detail')


그렇지 않다면, 아래와 같은 오류가 발생




Model.objects.get


- get 의 경우에는 ORM 에서 해당하는 조건들만 담기 때문에 객체들을 가지고 있어, for 문을 순회할 필요가 없다.

def remove_cart(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    cart = Cart.objects.get(cart_id=_cart_id(request))
    cart_item = CartItem.objects.get(product=product, cart=cart)
    if cart_item.quantity > 1:
        cart_item.quantity -= 1
        cart_item.save()
    else:
        cart_item.delete()
    return redirect('cart:cart_detail')