0

这是我modelsmanager班级。我认为问题出在PostingFilterManager下面。他们让我搜索关键字的方式titlebody_text错误的。我想在下面查询keywordsintitle和modelbody_text的列表。Postings我没有收到任何错误,但同时浏览器上没有显示任何内容。我确信过滤器应该返回一个帖子。

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)
4

1 回答 1

1

由于您构建查询的方式,这将不起作用。让我们分析您的查询:

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

您似乎想在内容和标题中搜索关键字。但这body_text__in=wordlist意味着如果您的整个文本为“hello”或“world”或“clean”,则过滤器将得到满足。我的假设是这不是你想要的。相反,您正在寻找的是迭代关键字和使用__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))

另外,补充建议。您在这里所做的是全文搜索,而您所做的可能不是最好的方法。可能更好的方法是构建索引并搜索索引。

考虑阅读有关全文搜索的维基百科文章,尤其是索引:http ://en.wikipedia.org/wiki/Full_text_search

于 2014-03-31T00:07:39.927 回答