title: Creating histogram bins from Django queries
body: <p>I'm trying to create bins with the count of prices to be used for a histogram. 
  I want the bins to be 0-1000, 1000-2000, 2000-3000 and so forth. If I just do group by I get way to many different bins.</p>
  
  <p>The code I've written seems to end in a infinite loop (or at least the script is still running after an hour). I'm not sure how to do it correctly. Here is the code I wrote:</p>
  
  <pre><code>from itertools import zip_longest
  
  def price_histogram(area_id, agency_id):
      # Get prices and total count for competitors
      query = HousePrice.objects.filter(area_id=area_id, cur_price__range=(1000,30000)).exclude(agency_id=agency_id)
      count = query.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price')
      total = query.count()
  
      # Get prices and total count for selected agency
      query_agency = HousePrice.objects.filter(area_id=area_id, agency_id=agency_id, cur_price__range=(1000,30000))
      count_agency = query_agency.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price')
      total_agency = query_agency.count()
  
      # Make list for x and y values
      x_comp = []
      y_comp = []
      x_agency = []
      y_agency = []
  
      bin_start = 0
      bin_end = 1000
      _count_comp = 0
      _count_agency = 0
  
      for row_comp, row_agency in zip_longest(count, count_agency, fillvalue={}):
          while bin_start &lt; int(row_comp['cur_price']) &lt; bin_end:
              _count_comp += row_comp['count']
              _count_agency += row_agency.get('count', 0)
          bin_start += 1000
          bin_end += 1000
  
          x_comp.append(str(bin_start) + "-" + str(bin_end) + " USD")
          x_agency.append(str(bin_start) + "-" + str(bin_end) + " USD")
          y_comp.append(_count_comp/total)
          y_agency.append(_count_agency/total_agency)
  
      return {'x_comp': x_comp, 'y_comp': y_comp, 'x_agency': x_agency, 'y_agency': y_agency}
  </code></pre>
  
  <p>I'm using Python 3.5 and Django 1.10.</p>