Django — implementing search facilities?

Good day!

models.py

 class Location(models.Model):
 user = models.ForeignKey(User)
 name = models.CharField(max_length=100, verbose_name=u"Location", default=u")
 keywords = models.CharField(max_length=100, verbose_name=u"Keywords")

forms.py

 class AdvancedSearchForm(forms.Form):
 location = forms.CharField()
 keywords = forms.CharField() # e.g. 'spam,eggs,hum'

views.py

 class AdvancedSearchView(FormView):
 form_class = AdvancedSearchForm
 template_name = "advanced_search.html"
 success_url = '/search_location/result/'

 # url of this view is 'search_result'
 class SearchResultView(ListView):
 model = Location
 context_object_name = 'locations_searched'
 paginated_by = 5
 template_name = "search_result.html"

 def get_queryset(self):
 queryset = super(SearchResultView, self).get_queryset()
 location = self.request.GET.get('location')
 location = location.upper()
 keywords = self.request.GET.get('keywords')
 return a queryset.filter(Q(name=location)|Q(keywords=keywords))

advanced_search.html

 <form action="{% url 'search_result' %}" method="GET">{% csrf_token %}
 {{ form|crispy }}
 <button class="btn btn-default" type="submit">Find</button>
</form>

search_result.html

 {% for location in locations_searched %}
 {{ location }}<br>
 {{ location.user }}<br>
 {{ location.keywords }}<br>
 {% endfor %}


The idea of this - when an object is created, the keywords stored in the database as a string of words separated by commas.
When you search for objects, I also fill the form field keywords of the comma separated words.
Question - how to implement the search of corresponding objects according to this algorithm, each word entered in the form should be searched for in each object (in the field keywords) and the coincidence of at least one word object to be returned.

P. S. as you can see, this implementation of Q(keywords=keywords) is looking for a comparison such as "spam,ham" with "eggs,ham,spam." And it is necessary, that would have "spam" and finding it "eggs,ham,spam," returned the object.

Thank you!
July 9th 19 at 10:25
2 answers
July 9th 19 at 10:27
Something like this:
filters = Q()

for word in keywords.split(','):
 filters |= Q(keywords__icontains=word)

Item.objects.filter(filters)
? what does |= - Mackenzie.Pfannersti commented on July 9th 19 at 10:30
: the operator OR
filters = filters | Q(keywords__icontains=word) - diamond.Reinger commented on July 9th 19 at 10:33
www.programiz.com/python-programming/operators#ass... - diamond.Reinger commented on July 9th 19 at 10:36
July 9th 19 at 10:29
models.py

 class Location(models.Model):
 user = models.ForeignKey(User)
 name = models.CharField(max_length=100)
 keywords = models.ManyToMany(Keyword)

 class Keyword(models.Model):
 name = models.CharField(max_length=100)

Find more questions by tags Django