Django ORM 注释计数项目并按特定顺序排序?

Django ORM Annotate Count Items and Order by Specific Order?

我有一张图表显示按地区划分的不同许可证类型以及每个地区有多少有效许可证。有没有办法在查询集中以特定顺序对项目进行排序以输出到图形?

这些是我的模型:

class Licence(models.Model):
    status = models.CharField(choices=STATUS, max_length=1000)
    number = models.CharField(unique=True, max_length=1000)
    licence_type = models.ForeignKey(
        "LicenceType", on_delete=models.SET_NULL, null=True
    )

class LicenceType(models.Model):
    region = models.ForeignKey(
        "Region", on_delete=models.SET_NULL, null=True
    )

class Region(models.Model):
    slug = models.SlugField(primary_key=True)

这是我的观点:

def dashboard(request):
    # total number of active licences across regions
    active_licences = (
        Licence.objects.values("licence_type", "licence_type__region")
        .annotate(total=Count("id"))
        .order_by("licence_type")
    )
    return render(request, "dashboard.html", "active_licences": active_licences)

有没有一种方法可以指定区域出现的顺序?例如,它们目前的顺序(按 pk)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 但我希望它们显示为 [1, 3, 2, 4, 5, 6, 7, 8, 9, 10].

我最终在视图中操作查询集中的数据,并将其作为元组列表返回给模板,如下所示:

def dashboard(request):
    # total number of active licences across provinces
    licences_by_province = list(
        Licence.objects.values("licence_type__region")
        .annotate(total=Count("id"))
        .order_by("licence_type")
    )

    # save provinces and totals to a list
    licence_list = []
    for province in licences_by_province:
        licence_list.append(tuple(province.values()))

    # re-order list to include ON, AB, BC at the beginning
    d = dict([('ON', 0), ('AB', 0), ('BC', 0)])
    d.update(dict(licence_list))
    active_licences = list(d.items())

    return render(request, "dashboard.html", "active_licences": active_licences)