Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order django charfield by alphabetical+numeric

I have the following a model, I already try to order_by('cell_name') but no same what I want. I want to order base on alphabet+number field. Could you please have your suggestions on this??, any help will be appreciated.

#my model

class BuildingCell(models.Model):
    ....
    cell_name = models.CharField(max_length=100, blank=True, null=True)

#my queryset
q1 = BuildingCell.objects.all().order_by('cell_name')

my result:

cell_name
10a
10b
10c
11a
11b
1a
1b
2a
2b

The result that I want:

1a
1b
2a
2b
10a
10b
11a
11b
like image 808
rahmat zaki Avatar asked Jan 30 '26 22:01

rahmat zaki


1 Answers

You can sort the queryset manually:

q1 = BuildingCell.objects.all()
q1 = sorted(list(q1),key=lambda s:list(map(lambda x:int(x) if x.isdigit() else x,re.split(r'(\d+)',s.name)[1:])))
like image 59
Arry Lee Avatar answered Feb 01 '26 12:02

Arry Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!