You cannot get them in a single request, but you can do something like this (you do not want to configure all env for testing, so use it as a hint, not a working solution):
beverages = Beverage.objects.order_by('name')
for beverage in beverages:
print each cell of your header
locations = Location.objects.all()
for location in locations:
print the location name table cell
location_beverages = iter(location.beverages.order_by('name'))
cur_bev = location_beverages.next()
for beverage in beverages:
if beverage == cur_bev:
print checked table cell
cur_bev = location_beverages.next()
else:
print empty table cell
Intermediate variables for storing requests are very important because they allow you to retrieve caching of Django requests.
With Django 1.4 or more, you can replace:
locations = Location.objects.all()
By:
locations = Location.objects.prefetch_related('beverages')
To get a serious boost.
source
share