0

我有模型时间,其中包含一个日期的时间。然后我有对象 Person,它是 Time 模型中的 ForeginKey 字段。我正在索引 Time 对象以查明 Person 在给定时间空间内是否有时间。

我试图将它添加到索引中,但是在建立索引时,我得到了错误:

def index_queryset(self, using=None):
    return self.get_model().objects.all().distinct('person')

错误:

DatabaseError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions

所以我只想显示人,而不是时间,但我认为我必须索引时间,所以我可以获得在给定日期间隔之间有时间的人。

4

2 回答 2

0

我自己解决了这个问题。出于某种原因,方法 build_queryset 覆盖了 order_by 子句,所以我不得不覆盖 build_queryset,请参阅我评论 order_by 子句的返回。

这是我放在索引类中的方法:

def build_queryset(self, using=None, start_date=None, end_date=None):
    """
    Get the default QuerySet to index when doing an index update.

    Subclasses can override this method to take into account related
    model modification times.

    The default is to use ``SearchIndex.index_queryset`` and filter
    based on ``SearchIndex.get_updated_field``
    """
    extra_lookup_kwargs = {}
    model = self.get_model()
    updated_field = self.get_updated_field()

    update_field_msg = ("No updated date field found for '%s' "
                        "- not restricting by age.") % model.__name__

    if start_date:
        if updated_field:
            extra_lookup_kwargs['%s__gte' % updated_field] = start_date
        else:
            warnings.warn(update_field_msg)

    if end_date:
        if updated_field:
            extra_lookup_kwargs['%s__lte' % updated_field] = end_date
        else:
            warnings.warn(update_field_msg)

    index_qs = None

    if hasattr(self, 'get_queryset'):
        warnings.warn("'SearchIndex.get_queryset' was deprecated in Haystack v2. Please rename the method 'index_queryset'.")
        index_qs = self.get_queryset()
    else:
        index_qs = self.index_queryset(using=using)

    if not hasattr(index_qs, 'filter'):
        raise ImproperlyConfigured("The '%r' class must return a 'QuerySet' in the 'index_queryset' method." % self)

    # `.select_related()` seems like a good idea here but can fail on
    # nullable `ForeignKey` as well as what seems like other cases.
    return index_qs.filter(**extra_lookup_kwargs)#.order_by(model._meta.pk.name)

def index_queryset(self, using=None):
    return self.get_model().objects.all().distinct('person').order_by('person')
于 2013-08-23T09:27:11.567 回答
0

尝试这个:

def index_queryset(self, using=None):
    return self.get_model().objects.all().order_by('person').distinct('person')
于 2013-08-22T18:18:07.513 回答