django - django排序问题
问题描述
我有一个由部分、小节和子句组成的文档。
Section 1
Subsections 1.1, 1.2, 1.3
Clauses 1.1.1, 1.1.2... 1.2.1, 1.2.2...
它们是具有“数字”字段来保存标识符的模型,但是由于某些小节和子句的双点语法,该字段是 CharField,例如...
Clause 1.2.1
如果我想对小节进行排序,Django 基本排序算法将排序:
1.1
1.2
1.3
...
但是当我在一个组中有超过 9 个小节或子句时就会出现问题,因为排序给了我:
1.1
1.10
1.11
1.2
1.3
...
有没有办法让这些在模板中正确排序,比如:
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11
我可以将它们转换为浮点数,然后对它们进行排序——但这不适用于子句。
模型.py
class Section(models.Model):
number = models.CharField(max_length=2, unique=True)
name = models.CharField(max_length=150, unique=False)
descriptor = HTMLField(blank=True)
def __str__(self):
return u'%s %s' % (self.number, self.name)
...
class Subsection(models.Model):
number = models.CharField(max_length=5, unique=True)
name = models.CharField(max_length=150, unique=False)
descriptor = HTMLField(blank=True)
fundamental = models.BooleanField()
section = models.ForeignKey(Section, on_delete=models.DO_NOTHING)
def __str__(self):
return u'%s %s' % (self.number, self.name)
class Meta:
ordering = ["number"]
....
class Clause(models.Model):
number = models.CharField(max_length=8, unique=True)
requirements = HTMLField()
audit_part = models.CharField(max_length=64, choices=AUDIT_CHOICES)
subsection = models.ForeignKey(Subsection, on_delete=models.DO_NOTHING)
compliance_level = models.CharField(max_length=64, choices=LEVEL_CHOICES, blank=True, null=True)
def __str__(self):
return u'%s' % (self.number)
class Meta:
ordering = ["number"]
...
解决方案
这是一种以这种方式排序的方法
from distutils.version import StrictVersion
subs = list(Subsection.objects.all().values_list("number", flat=True))
subs.sort(key=StrictVersion)
print subs
假设那subs
是["1.1", "1.10","1.11","1.2","1.3"]
这应该给你['1.1', '1.2', '1.3', '1.10', '1.11']
对查询集进行排序
subs = Subsection.objects.all()
result = sorted(subs, key=lambda x: StrictVersion(x.number))
推荐阅读
- typescript - 未找到 React Navigation Typescript 命名空间
- android - 配置根项目时出现问题
- sql - 按新命名的列对表中的列进行排序
- gcc - git bash 中的最大命令行长度
- ios - 分配 UITableView 内容以在 Swift iOS 中准备 segue
- git - 由于未合并文件与 git 子模块而无法提交
- entity-framework - 数据库优先中的Core 3.1 EF 6:无法确定多对多关系
- apscheduler - 测试一个job id是否存在APScheduler
- shell - 如何替换此 Zsh 表达式中的变量?
- python - 根据列表值间隔迭代列表