为什么我的搜索功能 return 出错 Related Field got invalid lookup: category

why is my search function return an error Related Field got invalid lookup: category

我的搜索功能工作正常,但每次我尝试在我的网站上搜索存在 post 时都会抛出一个错误。当我在 category 字段下的问题模型中删除 ForeignKey 时,错误消失了。请问我如何过滤具有 ForeignKey

的类别

错误:

FieldError at /index/
Related Field got invalid lookup: category

我的模特:

class Category(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False)

    def __str__(self):
        return str(self.name)


class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False) 
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Question, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

浏览量:

def index(request):
    query = request.GET.get('q', None)
    list_of_question = Question.objects.all()
    if query is not None:
        list_of_question = Question.objects.filter(
            Q(title__icontains=query) |
            Q(category__category__icontains=query)
        )
    unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count()

    paginator = Paginator(list_of_question, per_page=1)
    return render(request, 'index.html', {'unread_notifications':unread_notifications,'list_of_question':list_of_question, 'paginator':paginator})

我的表格:

<form action="" method="GET">
        <input placeholder="Search By Category" type="text" class="form-control" name="q">
    </form>

如果您使用 category__… 过滤,这意味着过滤器的其余部分应该处理 Category 模型的字段,并且 Category 有一个 name 字段, 所以你过滤:

list_of_question = Question.objects.filter(
    Q(title__icontains=query) |
    Q(<strong>category__name__icontains=query</strong>)
)