Django - 搜索表单

时间:2016-05-27 11:34:13

标签: django

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(TemplateView):
    template_name = "search_result.html"

    def get_context_data(self, **kwargs):
        context = super(SearchResultView, self).get_context_data(**kwargs)
        location = self.request.GET['location']
        location = location.upper()
        keywords = self.request.GET['keywords']
        # how should I use keywords (string of words split by commas)
        # in order to get locations_searched by name and keywords simultaneously
        locations_searched = Location.objects.filter(name=location)
        context['locations_searched'] = locations_searched
        return context

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 %}

请解释(或建议我在哪里查看)如何在模型和关键字中匹配关键字,以便按名称和关键字获取位置对象。

例如,某些对象可能会保留为关键字 - “垃圾邮件,鸡蛋”

在形式上,我只能输入'垃圾邮件'或'某些,垃圾邮件'

我希望在这种情况下得到这个对象

谢谢!

1 个答案:

答案 0 :(得分:0)

在您看来:

from django.db.models import Q

然后在get_context_data:

Location.objects.filter(Q(name=location) | Q(keywords=keywords))

您还可以在更多语句中构建 QuerySet ,方法是添加更多过滤器方法来构建复杂变体。