1

I am building a BlogApp and I am trying to add wordlist.txt at the place of exclude('wordlist.txt')

What i am trying to do :-

I build a feature of exclude posts according to words, For Example :- If a post contains word "Bad" then exclude that post like :-

from django.db.models import Q

posts = Post.objects.exclude(Q(description__contains='bad') & Q(description__contains='bad1'))

BUT i am trying to exclude hundreds of words at the same time AND when i add all of them in this way then it will be very lengthy AND i don't want that, So i think I can make a file named wordlist.txt and put all my words that i want to exclude then put the path of wordlist.txt in exclude query so i do not have to write lengthy exlcude words in the query.

For example :-

posts = Post.objects.exclude(description__contains=wordlist.txt)

( Above example is just to explain, what i am trying to do )

---------EDITED---------

I tried by reading file first then putting in exclude query Like :-

views.py

import os
from django.conf import settings

file_ = open(os.path.join(settings.BASE_DIR, 'wordlist.txt'))

def posts_exclude(request):
    posts = Post.objects.exclude(description__contains=file_)

    context = {'posts':posts}
    return render(request, 'mains/post_exclude.html', context)

wordlist.txt

good

BUT When i got to browser then unfortunately this is showing all the post without excluding.

I have no idea how can i do it .

Any help would be Appreciated.

Thank You in Advance

1 Answers1

0

You need to read the file wordlist.txt and then create a list with the words present in it.

with open('wordlist.txt') as in_file:
    wordlist = in_file.read().splitlines()  // assuming that your file contains a word per line

Then in your query you can use wordlist as:

posts = Post.objects.exclude(reduce(operator.and_, (Q(description__contains=x) for x in wordlist)))
Nalin Dobhal
  • 2,292
  • 2
  • 10
  • 20