[英]Only one word is reading from .txt file
我正在構建一個 BlogApp 並且我正在實現一個功能,
我正在嘗試做的事情:-
我正在嘗試閱讀和處理.txt
文件,但是當我寫一個單詞時它可以正常工作,但是當我寫兩個單詞時它不起作用。
視圖.py
def defining(request):
with open('wordlists.txt') as in_file:
wordlist = in_file.read().splitlines()
posts = Post.exclude.exclude(reduce(operator.and_,(Q(description__contains=x) for x in wordlist)))
context = {'posts':posts}
return render(request, 'defining.html', context)
單詞表.txt
good
bad
當我添加good
詞(只有一個詞)時,它可以正常工作,但是當我在好之后添加bad
詞時,兩者都不起作用。
我不知道,錯在哪里。 任何幫助,將不勝感激。 先感謝您。
我使用了operator._or而不是operator.and__
並且它工作正常。
在哪里operator.or_
?
from django.db.models import Q
from functools import reduce
def defining(request):
with open('wordlists.txt') as in_file:
wordlist = in_file.read().split()
posts = Post.objects.exclude(reduce(operator.or_,(Q(description__contains=x) for x in wordlist)))
HERE----------------------------------------------^
您應該使用operator._or
作為減速器,而不是operator._and
,因為您要排除包含單詞 good 或 bad 等的單詞。
您不需要使用reduce
,因為 Django 已經為Q
對象定義了一些算法。 您可以將其定義為:
posts = Post.objects.exclude(
Q(
*[Q(description__contains=x) for x in wordlist],
_connector=Q.OR
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.