Home > front end >  How do I target a ForeignKey attribute inside a loop?
How do I target a ForeignKey attribute inside a loop?

Time:11-26

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 %}

CodePudding user response:

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.

  • Related