简体   繁体   English

如何通过字母+数字订购django charfield

[英]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. 我有以下模型,我已经尝试过order_by('cell_name')但与我想要的不一样。 I want to order base on alphabet+number field. 我想根据alphabet+number字段订购。 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

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:])))

Assuming the data format outline is consistent with some number of digits followed by optional text you can parse data into 2 fields via regular expression and sort the resulting fields directly is the SQL statement. 假设数据格式轮廓与一定数量的数字一致,后跟可选文本,则可以通过正则表达式将数据解析为2个字段,并直接对所得字段进行排序(即SQL语句)。

with test_data (cell_name) as
   ( values ('10a')
          , ('10b')
          , ('10c')
          , ('11a')
          , ('11b')
          , ('1a')
          , ('1b')
          , ('2a')
          , ('2b')
          , ('20')      -- added 
          , ('20b')     -- added
          , ('ABC')     -- Use only for no leading digits passibility     
   )
select cell_name
 from  test_data 
 order by
       regexp_replace (cell_name, '^(\d+)(\D?.*)','\1')::integer
     , regexp_replace (cell_name, '^(\d+)(\D?.*)','\2') 
 ; 

If it's possible that an entry does not have leading digits then expand the order by clause: 如果某个条目可能没有前导数字,则展开order by子句:

select cell_name
 from  test_name 
 order by
         case when cell_name ~ '^(\d+)'
              then regexp_replace (cell_name, '^(\d+)(\D?.*)','\1')::integer
              else null::integer
         end
       , case when cell_name ~ '^(\d+)'
              then regexp_replace (cell_name, '^(\d+)(\D?.*)','\2')
              else cell_name
         end ; 

Converting to the appropriate Django/Python structure I'll have to leave to you as I don't know Django and little Python. 转换为适当的Django / Python结构后,我将不得不离开您,因为我不了解Django和很少的Python。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM