Home > front end >  Sorting sizes with two or more numbers in Django
Sorting sizes with two or more numbers in Django

Time:09-19

I am trying to sort items that have sizes described by two numbers like the following

10 x 13

100 x 60

7 x 8

The size is saved as a string. I want them sorted like this (first by first dimension, then by second dimension)

7 x 8

10 x 13

100 x 60

how can this be achieved with Django? It would be nice if we could somehow use

Item.objects.sort

CodePudding user response:

I would advice not to store these as a string, but as two IntegerFields, for example, with:

class Item(models.Model):
    width = models.IntegerField()
    height = models.IntegerField()

    @property
    def size(self):
        return f'{self.width}x{self.height}'

    @size.setter
    def size(self, value):
        self.width, self.height = map(int, value.split('x'))

Then you can easily sort by Item.objects.order_by('width', 'height') for example. We thus have a property .size that can format the item to a size, and even with a setter that can "parse" the value and put the width and height in the corresponding fields.

CodePudding user response:

you could use sorted for this from python math library. Had a similar problem way back this is what I used and it worked just fine.

import math
l = ['10x13', '100x60','7x8']
sorted(l, key=lambda dim: math.hypot(*map(int, dim.split('x'))))
# ['7x8', '10x13', '100x60']
  • Related