2016-05-27 14 views
0

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

、私は名前やキーワードでLocationオブジェクトを取得するために、モデルと形成するために入れたキーワードに合致するキーワードを行うことができますどのように説明し(または、私が見ることができる場所をアドバイスし)してください。

例えば、いくつかのオブジェクトがキーワードとして保持してもよい - 「スパムの卵」

と形で私は「スパム」または「いくつか、スパム」

を入力することができます私はこれを取得したいのですがこの場合、オブジェクト

感謝!あなたのビューで

答えて

0

from django.db.models import Q 

が続いget_context_dataに:

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

ます。また、複雑な変種を構築するために、よりフィルタメソッドを追加することによって、複数のステートメントであなたのクエリセットを構築することができます。

+0

ありがとうございます!私は方向性を持っていますが、私はまだ質問をしています。私たちはこのような種類の検索をしている表現Q(keywords = keywords)に - 例えば。あるユーザがオブジェクトを作成するときにKEYWORDSというフィールドに "spam、eggs"という文字列を入力すると、 "spam、stuff"という形式で検索します。この場合、検索は "spam、eggs" = "spam、stuff"のようになります。しかし、私は検索フォームのすべての単語に向かってモデル内のすべての単語を一致させる必要があります..私はいくつかの1つの単語に同意してもオブジェクトを取得したい – Dennis

+0

レコードの場合:IMOは多対1にキーワードをリファクタリングする方が良いです関係。とにかく;入力をカンマで区切って 'splitted_keywords'というリストを作成した後、リストをループしてクエリーセットに追加することで、テキストベースの検索を行うことができます:Q(keywords__contains = first_splitted_keywords [loopindex])) – acidjunk