python - 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,但到目前为止我还没有找到解决方案。
很感谢任何形式的帮助。
解决方案
您可以使用正则表达式进行过滤(使用 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)
推荐阅读
- python - Numpy - interp 函数如何工作?
- html - 找不到 PKG 和 DEB 的 HTML 下载文件
- conditional-operator - 不确定我是否理解这个嵌套的三元运算
- python - 如何在 tkinter slider.set 方法中设置一个值?
- amazon-web-services - Boto3 start_text_translation_job TooManyRequestsException
- javascript - JS 从缓冲区中读取字节
- c# - 如何从静态方法修改不同的类字段?
- c# - 我可以直接在 .cshtml 中为“asp-items”列表指定默认选项吗?
- django - 使用 Django 和 SMTP Google 发送电子邮件
- jquery - 将动态创建的输入值添加到数据库