Django / Taggit在数据库中包含所有标签和标题时搜索帖子

时间:2017-03-05 00:55:19

标签: python django search

我正在尝试为我的网站制作一个简单的搜索系统。我使用的是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并不适用于我。

2 个答案:

答案 0 :(得分:0)

在您的观看中尝试使用以下代码:

var

答案 1 :(得分:0)

您可能想要这样的东西:

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)