我有一个使用django的博客应用程序,其中包含以下模型
class Category(models.Model):
id=models.AutoField(primary_key=True)
title=models.CharField(unique=True,max_length=30,null=False,blank=False)
class Article(models.Model):
id=models.AutoField(primary_key=True)
title=models.CharField(max_length=100,null=False,blank=False)
category=models.ForeignKey(Category,null=False,blank=False)
summary=models.CharField(null=False,blank=False,max_length=400)
content = models.TextField(null=False, blank=False)
class Comment(models.Model):
id=models.AutoField(primary_key=True)
article=models.ForeignKey(Article,null=False,blank=False)
visitor_name=models.CharField(max_length=50,null=False,blank=False)
content=models.TextField(null=False,blank=False)
在管理区域,我尝试实施一个搜索引擎,允许管理员使用多个字段搜索评论。
我使用以下代码:
all_queries = None
keywords=''
search_fields = ('visitor_name','content','article__title','article__resume','article__category__title','article__content')
for keyword in keywords.split(' '):
keyword_query = None
for field in search_fields:
each_query = Q(**{field + '__icontains': keyword})
if not keyword_query:
keyword_query = each_query
else:
keyword_query = keyword_query | each_query
if not all_queries:
all_queries = keyword_query
else:
all_queries = all_queries & keyword_query
comments = Comment.objects.filter(all_queries).distinct().order_by('-date')
我遇到的问题是这一行:
search_fields = ('visitor_name','content','article__title','article__resume','article__category__title','article__content')
不知怎的,我得到一个空的查询集,因为我搜索了6个字段,因为我只能用2搜索。
例如这一行:
search_fields = ('visitor_name','content')
效果非常好,因为它只有两个搜索字段。
如果我只向阵列添加一个字段,那么它就不起作用
答案 0 :(得分:0)
我认为你的逻辑中存在一个小错误。您希望对每个关键字进行AND(&
)关键字查询,但目前您正在为每个字段进行AND运算。
降低构建all_queries
的代码的缩进级别:
all_queries = None
keywords=''
search_fields = ('visitor_name','content','article__title','article__resume','article__category__title','article__content')
for keyword in keywords.split(' '):
keyword_query = None
for field in search_fields:
each_query = Q(**{field + '__icontains': keyword})
if not keyword_query:
keyword_query = each_query
else:
keyword_query = keyword_query | each_query
# You only want to do this for each keyword
if not all_queries:
all_queries = keyword_query
else:
all_queries = all_queries & keyword_query
comments = Comment.objects.filter(all_queries).distinct().order_by('-date')