首页 > 解决方案 > 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"]
    ...

标签: django

解决方案


这是一种以这种方式排序的方法

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

推荐阅读