我在使用 Django QuerySet 时遇到问题:
为了不让搜索结果变得困惑,我首先使用以下代码从文本中删除所有 HTML 标记:
re.sub("<.*?>", "", note.text)
效果很好。
我需要修改所有笔记并在搜索完成后将它们恢复回来。
我尝试了这段代码:
def remove_tags(notes):
for note in notes:
note.text = re.sub("<.*?>", "", note.text)
return notes
notes = remove_tags(Note.objects.all()) # Remove HTML tags in all the notes
# ...
found = notes.filter( # By the some reason it restores default value here
Q(text__icontains=q) |
Q(title__icontains=q)
)
示例文本:
<span style="text-decoration:line-through">Todo</span>
当我在调用remove_tags后尝试立即访问文本时,一切似乎都很好:
notes = remove_tags(Note.objects.all())
print(notes[0].text) # Will print 'Todo'
但是当我在调用过滤器后执行此操作时,它看起来像以前一样:
notes = remove_tags(Note.objects.all())
print(notes[0].text) # Will print 'Todo'
filtered = notes.filter(text__icontains="line-through")
print(filtered[0].text) # Will print '<span style="text-decoration:line-through">Todo</span>'
如何过滤没有 HTML 标签的笔记?
最佳答案
filter
返回一个全新的 QuerySet,因此您在之前的 QuerySet 中更改的所有内容都将被忘记。
让我建议一种不同的方法:
class Note(models.Model):
text = models.TextField()
...
def text_without_tags(self):
return re.sub("<.*?>", "", self.text)
当您需要不带标签的字段内容时,请使用此方法。这更干净:就地修改变量是结束编写意大利面条代码的方法。
编辑:
尝试类似 Bleach而不是正则表达式。
关于python - Django中临时修改模型的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23982288/