我需要使用Django-filter或Elastic-search来过滤结果。我已经在我的应用程序中安装了两个。我使用过来自不同网站的教程,但结果并不像预期的那样。
我的Model.py:
class Wine(models.Model):
name = models.CharField(max_length=200)
release_date = models.DateTimeField(default=datetime.datetime.now)
我的filter.py:
from django import forms
from .models import Manufacturer, Wine
import django_filters
class WineFilter(django_filters.FilterSet):
release_date = django_filters.NumberFilter(name='release_date', lookup_expr='year')
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Wine
fields = ['name', 'release_date']
我的view.py:
def search(request):
wine_list = Wine.objects.all()
wine_filter = WineFilter(request.GET, queryset=wine_list)
return render(request, 'reviews/wine_list.html', {'filter': wine_filter})
如果使用弹性搜索:我的search_filters.py
class WineIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
release_date = indexes.CharField(model_attr='release_date')
def get_model(self):
return Wine
def index_queryset(self, using=None):
return self.get_model().objects.all()
我的form.py:
from django.forms import ModelForm, Textarea
from haystack.forms import SearchForm
class WineSearchForm(SearchForm):
def no_query_found(self):
return self.searchqueryset.all()
通常,要显示葡萄酒列表,我将其放在我的HTML中:
{% for wine in wine_list %}
<div class="panel panel-default">
<div class="panel-body">
{{ wine.name }} - {{ wine.release-date }}
</div></div>
{% endfor %}
但是,我想用实际wine_list.html左侧的侧面板过滤结果。大部分选择都将通过选择框完成:
<!-- third Panel start Here -->
<div class="panel panel-default">
<h4 class="panel-title">Year Of Manufacture</h4>
<div class="list-group">
{{ filter.form.release_date.label_tag }}
{% for choice in filter.form.release_date %}
<label class="checkbox-inline">
{{ choice.tag }} {{ choice.choice_label }}
</label>
{% endfor %}
<div class="checkbox">
<label><input type="checkbox" value="">2016</label>
</div>
<div class="checkbox">
<label><input type="checkbox" value="">2015</label>
</div>
</div>
</div>
我修改了wine_list.html来渲染结果但不起作用:
{% for wine in filter.qs %}
<tr>
<td>{{ wine.name }}</td>
<td>
{% for release_date in wine.release_date.all %}
{{ wine.release_date }}
{% empty %}
<em class="text-muted">No release_date</em>
{% endfor %}
</td>
</tr>
{% empty %}
<tr>
<td colspan="5">No data</td>
</tr>
{% endfor %}
通过解决我的错误,它可以解决我的大多数问题,因为我希望为我的模型的几个选择框。