【问题标题】:Django haystack+whoosh errorDjango haystack+whoosh 错误
【发布时间】:2014-03-27 17:29:41
【问题描述】:

我正在尝试在我的 django 应用程序中进行搜索,然后我使用了 haystackwhoosh 但我遇到了一些麻烦。首先,当我尝试重建索引或更新索引时,它在下面给了我这个错误,第二个是当我输入和搜索时它给了我 0 个结果。所以我只是想,如果这个rebuild_index 修复了搜索问题就会得到解决。请任何人帮助我解决这个问题

错误:

/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py:903: RuntimeWarning: DateTimeField Subtitle.pub_date received a naive datetime (2014-03-27 16:36:44.341555) while time zone support is active.
  RuntimeWarning)

Indexing 14 Subtitles
ERROR:root:Error updating sub using default 
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 221, in handle_label
    self.update_backend(label, using)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 267, in update_backend
    do_update(backend, index, qs, start, end, total, self.verbosity)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 89, in do_update
    backend.update(index, current_qs)
  File "/usr/local/lib/python2.7/dist-packages/haystack/backends/whoosh_backend.py", line 179, in update
    doc = index.full_prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/indexes.py", line 204, in full_prepare
    self.prepared_data = self.prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/indexes.py", line 195, in prepare
    self.prepared_data[field.index_fieldname] = field.prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/fields.py", line 99, in prepare
    raise SearchFieldError("The model '%s' has an empty model_attr '%s' and doesn't allow a default or null value." % (repr(obj), attr))
SearchFieldError: The model '<Subtitle: 3 idiots>' has an empty model_attr 'pub_date' and doesn't allow a default or null value.
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/rebuild_index.py", line 16, in handle
    call_command('update_index', **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 159, in call_command
    return klass.execute(*args, **defaults)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 195, in handle
    return super(Command, self).handle(*items, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in handle
    label_output = self.handle_label(label, **options)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 221, in handle_label
    self.update_backend(label, using)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 267, in update_backend
    do_update(backend, index, qs, start, end, total, self.verbosity)
  File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 89, in do_update
    backend.update(index, current_qs)
  File "/usr/local/lib/python2.7/dist-packages/haystack/backends/whoosh_backend.py", line 179, in update
    doc = index.full_prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/indexes.py", line 204, in full_prepare
    self.prepared_data = self.prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/indexes.py", line 195, in prepare
    self.prepared_data[field.index_fieldname] = field.prepare(obj)
  File "/usr/local/lib/python2.7/dist-packages/haystack/fields.py", line 99, in prepare
    raise SearchFieldError("The model '%s' has an empty model_attr '%s' and doesn't allow a default or null value." % (repr(obj), attr))
haystack.exceptions.SearchFieldError: The model '<Subtitle: 3 idiots>' has an empty model_attr 'pub_date' and doesn't allow a default or null value.

我的 models.py 是

class Movies(models.Model):
    name = models.CharField(max_length=100)
    poster = models.FileField(upload_to="posters/")
    date = models.CharField(max_length=4)
    director = models.CharField(max_length=30, blank=True, null=True)
    actors = models.CharField(max_length=360, blank=True, null=True)
    music = models.CharField(max_length=200, blank=True, null=True)
    company = models.CharField(max_length=200, blank=True, null=True)

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name_plural = 'Movies'


class Subtitle(models.Model):
    name=models.ForeignKey(Movies, related_name="subtitles")
    extension=models.CharField(max_length=5, choices=sub_choices)
    upload=models.FileField(upload_to="subtitles/%Y/%m/%d/")
    user=models.ForeignKey(User)
    pub_date=models.DateTimeField('published', default='')
    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name_plural = 'Subtitles' 

我的views.py是

def Subtitle_search(request):
    form = SubtitlesSearchForm(request.GET)
    results = form.search()

    return render(request, 'search/search.html', {
        'search_query':search_query,
        'subtitles':results,
        })

app 文件夹中的search_index.py/* 放在我的app 文件夹中是否正确? */

class SubtitleIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='user')
    pub_date = indexes.DateTimeField(model_attr='pub_date')

    def get_model(self):
        return Subtitle

    def index_queryset(self, using=None):
        return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())

和forms.py

​​>
class SubtitlesSearchForm(SearchForm):

    def no_query_found(self):
        return self.searchqueryset.all()

    def search(self):
        # First, store the SearchQuerySet received from other processing. (the main work is run internally by Haystack here).
        sqs = super(SubtitleSearchForm, self).search()

        # if something goes wrong
        if not self.is_valid():
            return self.no_query_found()

        # you can then adjust the search results and ask for instance to order the results by title
        sqs = sqs.order_by(name)

        return sqs

模板/搜索/search.html

{% extends 'index.html' %}

{% block content %}
<div class="row">
    <h2>Search</h2>

    <form method="get" action=".">
        <table>
            {{ form.as_table }}
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Search">
                </td>
            </tr>
        </table>

        {% if query %}
                <h3 class="results">Results</h3>

            {% for result in page.object_list %}
                <p>
                    <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
                </p>
            {% empty %}
                <p>No results found.</p>
            {% endfor %}

            {% if page.has_previous or page.has_next %}
                <div>
                    {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %}
                    |
                    {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
                </div>
            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}
    </form>
    </div>
{% endblock %}

最终模板/搜索/索引/sub/subtitle_text.txt

{{ object.name }}

【问题讨论】:

    标签: python django django-haystack whoosh


    【解决方案1】:

    你的错误是:

    haystack.exceptions.SearchFieldError: The model '<Subtitle: 3 idiots>' has an empty model_attr 'pub_date' and doesn't allow a default or null value.
    

    Haystack 表示特定模型的 pub_date 字段为空,但您尚未指定 pub_date 字段可以为空。

    您可以通过设置 null=True 告诉 haystack pub_date 字段可以为空来解决此问题,如下所示:

    class SubtitleIndex(indexes.SearchIndex, indexes.Indexable):
        ...
        pub_date = indexes.DateTimeField(model_attr='pub_date', null=True)
    

    【讨论】:

    • 嗨@Sohan-jain 谢谢,它真的很有帮助,最终我可以做rebuild_index,但不幸的是又出现了问题。它说RuntimeWarning: DateTimeField Subtitle.pub_date received a naive datetime (2014-03-27 19:41:52.460417) while time zone support is active. RuntimeWarning)
    • 首先请注意,可以忽略该消息,因为它是警告而不是错误。日期时间在 Django 中真的很难搞定。有时区感知的和没有时区信息的。当您编制索引时,您处于没有时区支持的日期时间中。一般来说,你想在任何地方使用:“from django.utils import timezone”,然后用“timezone.now()”代替“datetime.datetime.now()”
    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多