2013-08-22 66 views
0

我有模型時間,其中包含一個日期的時間。然後我有對象Person,它是Time模型中的ForeginKey字段。我將時間對象編入索引以查明Person是否在給定的時間空間中有時間。Django草垛搜索之間的時間和只顯示ForeignKey結果

我試圖把它添加到索引,但索引的時候,我得到錯誤:

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 

所以我想只能顯示的人,沒有時間,但我想我必須索引時間,所以我可以得到在給定日期間隔之間有時間的人。

+0

我有點困惑你想才達到的。你可以擴展一點,並分享一些你的代碼?你的models.py是怎樣的?該方法去哪裏?爲什麼你需要時間成爲一個不同的模型,而不是'人'的領域?您希望查詢搜索結果看起來像什麼? – yuvi

回答

0

我解決了這個自己。由於某種原因,build_queryset覆蓋了order_by子句,所以我不得不重寫build_queryset,請參閱return where 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') 
0

試試這個:

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