How do I target a ForeignKey attribute inside a loop?

Question:

I’ve a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock,
the code for not authenticated users works, but for authenticated users Traceback Error is 'OrderItem' object has no attribute 'availability'

Models

class Product(models.Model):
    availability = models.BooleanField()

class OrderItem(models.Model):
    product = models.ForeignKey(Product)
    order = models.ForeignKey(Order)

Views

def cart(request):
    data = cartData(request)
    items = data['items']

    orderitemlist = OrderItem.objects.all()

    if not request.user.is_authenticated:
        available = all(x['product']['availability'] for x in items)
    else:
        available = all(x.availability for x in orderitemlist)

    context = {"items": items, 'available': available}

Template

{% if available %}
    <a href="#">Checkout</a>
{% else %}
    <p>Out of stock</p>
{% endif %}
Asked By: betty_

||

Answers:

You check the availability of the product, so:

def cart(request):
    data = cartData(request)
    items = data['items']

    orderitemlist = OrderItem.objects.select_related('product')

    if not request.user.is_authenticated:
        available = all(x['product']['availability'] for x in items)
    else:
        available = all(x.product.availability for x in orderitemlist)

    context = {'items': items, 'available': available}

The .select_related(…) clause [Django-doc] is not really necessary, but will fetch all the products in the same query and thus will boost processing.

Answered By: Willem Van Onsem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.