0

這是我的modelsmanager類。我認爲問題出在下面的PostingFilterManager。他們的方式我搜索關鍵字titlebody_text是錯誤的。 我想查詢下面Postings模型的titlebody_text中的keywords列表。我沒有收到任何錯誤,但同時沒有任何顯示在瀏覽器上。我相信過濾器應該會返回一個帖子。定製管理器對象不在Django中工作?

class PostingFilterManager(models.Manager): 
    def get_by_keywords(self,wordlist): 
     print "called" 
     posts=super(PostingFilterManager,self).get_query_set().filter 
     (Q(body_text__in=wordlist) | Q(title__in=wordlist)) 
     print posts 
     return posts 

class Postings(models.Model): 
    carinfo=models.ForeignKey('CarInfo') 
    title = models.CharField(max_length=100, blank=True) 
    body_text = models.TextField(blank=True)  
    objects=models.Manager() 
    filters=PostingFilterManager() 

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

my view:

def detail(request,year): 
    result=Postings.filters.get_by_keywords(['hello'.'world','clean']) 
    return HttpResponse(result) 
+0

'...過濾器 - 不要你的意思'...過濾器( carinfo__in = CarInfo.objects.filter(year__lte =年))'? – lanzz

+0

@lanzz:這有助於感謝。但我有關於這個問題編輯的相關問題。我的視圖將關鍵字列表傳遞給管理器對象,然後應該過濾這些關鍵字的標題和正文,我沒有得到此正常工作,請幫助 –

+0

您是在這裏複製並粘貼您的代碼,還是在鍵入內容它再次手工?因爲'['hello','world','clean']'會因''hello''和''world''之間的點引發'SyntaxError'異常。 – lanzz

回答

1

這不會因爲你是如何構造的查詢工作。讓我們來分析查詢:

filter(Q(body_text__in=wordlist) | Q(title__in=wordlist)) 

看來你要搜索的內容和標題的關鍵字。但是body_text__in=wordlist意味着如果你的整個文本將是'你好'或'世界'或'乾淨',那麼過濾器將會被滿足。我的假設是,這不是你想要的。相反,您正在尋找的是迭代關鍵字並使用__contains條件。我沒有寫在相當長的一段Django的查詢,所以我會寫一些醜陋的代碼,也許會出現總體思路:

full_query = null 
for keyword in wordlist: 
    if full_query is null: 
    full_quey = Q(body_text__contains=keyword) | Q(title__in=keywords) 
    else: 
    full_query = full_query | (Q(body_text__contains=keyword) | Q(title__in=keywords)) 
posts=super(PostingFilterManager,self).get_query_set().filter 
     (Q(body_text__in=wordlist) | Q(title__in=wordlist)) 

而且,額外的建議。你在這裏做的是全文搜索,你在做什麼可能不是做這件事的最好方式。可能更好的方法是構建索引並搜索索引。

考慮有關全文檢索閱讀維基百科的文章,尤其是索引:((year__lte =年)CarInfo.objects.filter)`http://en.wikipedia.org/wiki/Full_text_search

+0

感謝您的回覆。你能否通過構建和索引來詳細說明你的意思,並搜索索引。或解釋這個的任何鏈接?謝謝 –

+0

我添加了維基百科文章,它應該給你一個基本的概述。 – gruszczy