Accessing "products" from prefetch_related queryset

Hello,

I am wondering how to access fields from the Product model from the queryset below:

queryset = Order.objects.select_related(‘customer’).prefetch_related(‘orderitem_set__product’).filter(customer_id=241)

I hace tried multiple different combinatios to no avail, such as:

  • {{ order.orderitem_set.product }}
  • Please help!

    Thank you,
    Jean

    To be able to access product instances and their fields using the query above,
    You need to convert this queryset object to a list.
    This list will contain all the order objects this queryset finds in the database.
    For example if there are 2 orders placed by customer 241, then we will have those 2 orders in our list.
    Then we can use a for loop to iterate over the contents of this list and get their items.
    Inside this for loop we write another for loop to get each item in the list of all order items of the current order…
    Then we can access the product of each order item.

    In this example I accessed the unit_price of each product in the order.

    Here is my implementation, just note that I changed the related_name from orderitem_set to items:

            queryset = Order.objects.select_related('customer').prefetch_related('items__product').filter(customer_id=1)
                
            for order in list(queryset):
    
                [print(item.product.unit_price) for item in order.items.all()]
    

    you can access products inside template using this code:

    <ul>
          {% for order in orders %}
              <h4>Order_id: {{ order.id }} - Customer_name: {{order.customer.first_name}} - payment: {{order.payment_status}}</h4>
              <span>Order_items:</span>
              <ul>
                  {% for item in order.orderitem_set.all %}
                      <li>title: {{item.product.title}} - unit_price: {{item.product.unit_price}} </li>
                  {% endfor %}
              </ul>
          {% endfor %}
      </ul>```
    
    inside the object we have structures like this:
    
    

    orders = [
    {
    ‘id’: 1,
    ‘placed_at’: datetime.datetime(2022, 1, 1, 12, 0, 0),
    ‘payment_status’: ‘C’,
    ‘customer’: {
    ‘id’: 123,
    ‘name’: ‘John Doe’,
    # Other customer fields
    },
    ‘orderitem_set’: [
    {
    ‘id’: 456,
    ‘quantity’: 2,
    ‘product’: {
    ‘id’: 789,
    ‘name’: ‘Product 1’,
    # Other product fields
    }
    },
    # Other OrderItem objects
    ]
    },
    # Other Order objects
    ]