Django 3:过滤字母或非字母的查询集

joh*_*nes 4 python django django-queryset

在我的数据库中,我有一个表,其中包含标题可以以字母或非字母字符开头的项目。例如数字或“@”或“#”。该模型如下所示:

class Items(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField
Run Code Online (Sandbox Code Playgroud)

在我看来,我想将模型分成两个对象。一个对象包含标题以字母开头的所有项目,另一个对象包含所有其他项目:

class ItemsView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        alpha_list = Items.objects.filter(title__startswith=<a letter>)
        other_list = Items.objects.filter(title__startswith=<not a letter>)

        context = {
            "list_a": alpha_list,
            "list_b": other_list
        }

        return context
Run Code Online (Sandbox Code Playgroud)

我一直在查阅文档、stackoverflow和神圣的google,但到目前为止我还没有找到解决方案。

很感谢任何形式的帮助。

Lin*_*yen 6

您可以使用正则表达式进行过滤(使用 regex101.com 来测试您的正则表达式)并排除以查找其他不以字母开头的项目

\n

以字母开头:

\n
alpha_list = Items.objects.filter(title__regex=r\'^[a-zA-Z].*$\')\n
Run Code Online (Sandbox Code Playgroud)\n

其他情况:

\n
other_list = Items.objects.exclude(title__regex=r\'^[a-zA-Z].*$\')\n
Run Code Online (Sandbox Code Playgroud)\n

解释:

\n
/^[a-zA-Z].*$/\n\n^ asserts position at start of the string \n\na-z a single character in the range between a (index 97) and z (index 122) (case sensitive) \n\nA-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive) \n\n.* matches any character (except for line terminators)\n\n* Quantifier \xe2\x80\x94 Matches between zero and unlimited times, as many times as possible, giving back as needed \n\n$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)\n
Run Code Online (Sandbox Code Playgroud)\n