如何通过搜索词Django获取数据

时间:2017-11-19 11:17:35

标签: django django-forms django-rest-framework

我在将数据发送到主页时遇到问题。 我想过滤掉基于流派的所有书籍。我跟着他 MDN site为此。

的index.html

{% extends "base_generic.html" %}

{% block content %}
<h1>Local Library Home</h1>

  <p>Welcome to <em>Local Library</em>, a very basic Django website.</p>

<h2>Dynamic content</h2>
<form action="" method="get">
   <input type="text" name="genre" placeholder="Search">
   <input type="submit" value="Search">
</form>
{% endblock %}

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^books/$', views.BookListView.as_view(), name='books'),
    url(r'^(?P<string>[-\w]+)$', views.GenreListView.as_view(), name='index'),
]

GenreListView类

class GenreListView(generic.ListView):
    model = Book
    def get(request, string):
       try:
           book = Book.objects.all().filter(genre=string)
       except Book.DoesNotExist:
           raise Http404("Book does not exist")

     return render(
        request,
        'index.html',
        context={'book': book,}
    )

我无法弄清楚我错过了什么,或者我还需要做些什么才能根据流派获得所有日期?

编辑: 整个 index.html

{%  extends "base_generic.html" %}

{%  block content %}
    <h1> Book List </h1>

    <form action="" method="get">
        <input type="text" name="genre" placeholder="Search">
        <input type="submit" value="Search">
    </form>

    {% if book_list %}
    <ul>
        {% for book in book_list %}
        <li>
            <a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{ book.author }})
        </li>
        {% endfor %}
    </ul>
    {% else %}
        <p>There are no books in the library</p>
    {% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:2)

您应该覆盖get_queryset,无需重写get

class GenreListView(generic.ListView):
    model = Book
    template_name = 'index.html'

    def get_queryset(self):
        books = Book.objects.all()
        query = self.request.GET.get('genre', None)
        if query:
           return books.filter(genre=query)
        return books
  

例外 Book.DoesNotExist 永远不会   如果您 filter() 查询集,则会出现此问题。如果没有找到对象,它将始终返回一个空的查询集