首页 > 解决方案 > Django 3:过滤字母或非字母的查询集

问题描述

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

class Items(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField

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

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

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

很感谢任何形式的帮助。

标签: pythondjangodjango-queryset

解决方案


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

以字母开头:

alpha_list = Items.objects.filter(title__regex=r'^[a-zA-Z].*$')

其他情况:

other_list = Items.objects.exclude(title__regex=r'^[a-zA-Z].*$')

解释:

/^[a-zA-Z].*$/

^ asserts position at start of the string 

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive) 

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive) 

.* matches any character (except for line terminators)

* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed 

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

推荐阅读