我有一个Article
模型,可以收集用户的文章。这些文章中可以包含 #hashtags ,就像我们在twitter中一样。我将这些主题标签转换为链接,用户可以单击这些链接来加载所有包含已点击主题标签的文章。
如果我将这些文章保存在Article
模型中:
1. 'For the love of learning: why do we give #Exam?'
2. 'Articles containing #Examination should not come up when exam is clicked'
3. 'This is just an #example post'
我尝试使用Django' __icontains
过滤器
def hash_tags(request, hash_tag):
hash_tag = '#' + hash_tag
articles = Articles.objects.filter(content__icontains=hash_tag)
articles = list(articles)
return HttpResponse(articles)
但如果用户点击#exam
,则会返回三篇文章而不是第一篇。
我可以在'#exam'成为' #exam'它会很好,但我希望能用正则表达式做到这一点。
我试过了:
articles = Articles.objects.filter(content__iregex=r"\b{0}\b".format(hash_tag))
但我得到空洞的回应。
如何才能使其正常工作?我在后端使用Django 1.6和MySQL。
答案 0 :(得分:2)
我建议您删除第一个\b
,因为#
和空格之间不存在单词boudary。即,如果hash_tag
变量的值为#exam
,则r"\b{0}\b"
将生成正则表达式\b#exam\b
。并且这不会匹配空间旁边的#exam
,因为空格和#
之间不存在单词边界,因此它会失败。 #
和空格是非单词字符。 \b
匹配单词字符和非单词字符。
content__iregex=r"{0}\b".format(hash_tag)
如有必要,添加不区分大小写的修饰符。
content__iregex=r"(?i){0}\b".format(hash_tag)
答案 1 :(得分:0)
我终于能够做到这一点。
articles = Articles.objects.filter(content__iregex=r"^[^.]*{0}*[[:>:]]".format(hash_tag))
就是这样!