Accessing "products" from prefetch_related queryset


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,

    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()]