[Answer]-Django use ORM to get range of a particular element

1👍

Pretty certain you can’t do that with the ORM…you’ll need to write your own python code to do that.

counts = []

for model in MyModel.objects.all().order_by('value'):
  if not counts or last_item != model.item:
    counts.append({'item': model.item, 'values': [ model.value ]})
    last_item = model.item
  elsif model.item == last_item:
    counts[-1]['values'].append(model.value)

for count in counts:
  count['values'] = '%s-%s' % (count['values'][0], count['values'][-1])

Edit:

counts = []

for model in MyModel.objects.all().order_by('value'):
  if not counts or last_item != model.item:
    counts.append({'item': model.item, 'first': model.value, 'last':model.value})
    last_item = model.item
  elsif model.item == last_item:
    counts[-1][last] = model.value

Leave a comment