Django:按字母顺序分页时将所有数字数据连接到一个查询集中的最简单方法?

Django: Easiest way to join all numerical data into one QuerySet when doing alphabetical pagination?

我正在尝试将查询结果按字母顺序排序,如下所示:

这适用于以下代码:

    def get_context(self, request):
        # Get published shows, ordered alphabetically
        context = super().get_context(request)
        shows = ShowPage.objects.child_of(self).live().order_by("name")
        context["pages"] = [{"letter" : i, 
                            "shows" : shows.filter(name__istartswith=i.upper())}
                            for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
        return context

下一步是将所有以任意数字开头的节目合并到一个标记为“0-9”的组中。

以下是我想要的,但它非常冗长,我想知道是否有更简单的方法,我只是不知道:

def get_context(self, request):
        # Get published shows, ordered alphabetically
        context = super().get_context(request)
        shows = ShowPage.objects.child_of(self).live().order_by("name")
        pages = [{"letter" : i, 
                            "shows" : shows.filter(name__istartswith=i.upper())}
                            for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
        digits = {"letter" : "0 - 9", "shows" : []}
        for index, alphabet in enumerate(pages):
            if alphabet["letter"].isdigit():
                for show in alphabet["shows"]:
                    digits["shows"] += [show]
        while pages[0]["letter"].isdigit():
            print(pages[0])
            pages.pop(0)
        pages.insert(0, digits)
        context["pages"] = pages
        return context

有什么想法吗?

只需在字段搜索中使用简单的 one-line 正则表达式即可查看名称字符串是否以数字开头。另外 istartswith 是 case-insensitive 所以你不需要 i.upper().

def get_context(self, request):
        # Get published shows, ordered alphabetically
        context = super().get_context(request)
        shows = ShowPage.objects.child_of(self).live().order_by("name")
        context['pages'] = [{'letter': shows.filter(name__istartswith=letter)} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
        context['pages'].append({'letter': '0-9', 'shows': shows.filter(name__regex=r'^\d[\w\d _-]+'})
        return context