Answer the question
In order to leave comments, you need to log in
Django - implementation of object search?
Good afternoon!
models.py
class Location(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'')
keywords = models.CharField(max_length=100, verbose_name=u"Ключевые слова")
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 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 %}
Answer the question
In order to leave comments, you need to log in
More or less like this:
filters = Q()
for word in keywords.split(','):
filters |= Q(keywords__icontains=word)
Item.objects.filter(filters)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question