相关字段的查找无效:​​icontains - While Search Tag

Related Field got invalid lookup: icontains - While Search Tag

我正在构建一个 BlogApp,我正在尝试实现一个搜索字段,该字段将使用输入的 tag.

进行搜索(过滤)

当我尝试访问该页面时,它一直显示

Related Field got invalid lookup: icontains

models.py

class BlogPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30,default='')
    tags = TaggableManager()

views.py

from taggit.models import Tag

def search_page(request):
    query = request.GET.get('p')
    object_list = BlogPost.objects.filter(tags__icontains=query)

    context = {'posts': object_list, 'query': query}
    return render(request, 'search.html', context)

我也尝试过不同的方法,但仍然显示相同的错误。

NoneType' object is not iterable

Related Field got invalid lookup: icontains

任何帮助将不胜感激。提前致谢。

您应该指定您正在查看标签的 名称,因此:

object_list = BlogPost.objects.filter(<strong>tags__name__icontains=query</strong>)

您应该仅在有查询时进行过滤,因此:

from taggit.models import Tag

def search_page(request):
    query = request.GET.get('p')
    object_list = BlogPost.objects.all()
    if <strong>query is not None</strong>:
        object_list = object_list.filter(tags__icontains=query)
    context = {'posts': object_list, 'query': query}
    return render(request, 'search.html', context)

您可能还想使用 q 而不是 p 作为查询参数名称。