gpt4 book ai didi

python - Django 3 : Filter queryset for letter or non-letter

转载 作者:行者123 更新时间:2023-12-04 02:31:02 27 4
gpt4 key购买 nike

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

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 和神圣的谷歌,但到目前为止我还没有找到解决方案。
很感谢任何形式的帮助。

最佳答案

您可以使用 regex过滤(使用 regex101.com 测试您的正则表达式)和 exclude查找其他不以字母开头的项目
以字母开头:

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 - Django 3 : Filter queryset for letter or non-letter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64168634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com