【发布时间】:2015-02-19 08:50:26
【问题描述】:
我有一个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。
【问题讨论】: