【问题标题】:Django/Taggit Searching for posts when all tags and title are contained in the database当所有标签和标题都包含在数据库中时,Django / Taggit搜索帖子
【发布时间】:2017-03-05 00:55:18
【问题描述】:

我正在尝试为我的网站制作一个简单的搜索系统。我正在使用python 3.6Django 1.10.5Taggit 0.22.0。当我在搜索表单中输入标签时,我希望它查询数据库并返回标签或标题至少包含搜索到的任何标签的任何帖子。

例如:/search/?q=random%2C+stuff

会返回:

Post1 {Title: "How to be funny" Tags: "Random", "isn't", "Funny"}

Post2 {Title: "How to make Stuffed Turkey" Tags: "Cooking", "Thanksgiving"}

models.py

class Post(models.Model):
    title = models.CharField(max_length=256)
    tags = TaggableManager()

    def __str__(self):
        return self.title

views.py

def index(request):

    query = request.GET.get('q')

    if (query == None or not query):
        tags = Post.tags.most_common()[:10]
        return render(request, 'search/search.html', {'tags':tags})
    else:
        queryList = query.split(',')
        results = # Query the database to get results
        return render(request, 'search/results.html', {'query':query, 'results':results})

我一直在寻找在 django 中实现此查询的最佳方法

而且结果应该是大小写密集型的,将TAGGIT_CASE_INSENSITIVE = True 插入settings.py 对我不起作用。

【问题讨论】:

    标签: python django search


    【解决方案1】:

    在您的视图中尝试以下代码:

    from django.db.models import Q
    q = request.GET['q'].split()  # I am assuming space separator in URL like "random stuff"
    
    query = Q()
    for word in q:
        query = query | Q(title__icontains=word) | Q(tags__name__icontains=word)
    results = Post.objects.filter(query)
    

    【讨论】:

      【解决方案2】:

      你可能想要这样的东西:

      def products_search(request):
          ''' If I am intending to use this in other places also ,I should better put this  in Model Manager'''
          query_original=request.GET.get('q',None)
          search_query = query_original.lower().split()
          if len(search_query)>=1:
              for word in search_query:
                  lookups = Q(title__icontains=word) | Q(description__icontains=word) Q(tags__name__icontains=word)
          queryset     = Product.objects.filter(lookups,is_active=True).distinct() 
          context      = {'object_list':queryset}
          return render(request,'products/product_search.html',context)
      

      【讨论】:

      • 您的for loop 代码不正确。它只会搜索列表中的最后一个单词,因为变量lookups 在每次迭代中都会被覆盖。另外,不需要检查长度,你可以写:if search_query:
      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 2019-09-27
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多